如何用一个词替换不同的短语 - python



在学习python时,我弄乱了replace((方法并尝试制作这个程序:

message = raw_input("Message to find the part of speech: ")
coordconj = "for" or "and" or "nor" or "but" or "or" or "yet" or "so"
print message.replace(coordconj, "coordinating conjunction")

如果我使用输入"名称 1 表示名称 2"运行它。输出是"name1 协调连词 name2",但以"name1 和 name2"作为输入,它打印"name1 和 name2">

我也试过:

message = raw_input("Message to find the part of speech: ")

print message.replace("for" or "and" or "nor" or "but" or "or" or "yet" or "so", "coordinating conjunction")

但这也没有用。它只是用"协调连词"代替"for"。有没有办法让变量中的所有单词coorcon替换为"协调连词"而不使用一堆 if 语句?提前谢谢。

"for" or "and" or "nor" or "but" or "or" or "yet" or "so"

只是"for",因为非空字符串在 Python 中是 Truthy 并且or是懒惰地计算的。

您可以在 Python 控制台中签到:

>>> "for" or "and" or "nor" or "but" or "or" or "yet" or "so"
'for'

这是解决问题的可能方法:

import re
def find_speech_part(matchobj):
  word = matchobj.group(0)
  if word.lower() in ["for","and","nor","but","or","yet","so"]:
    return "coordinating conjunction"
  else:
    return word
print(re.sub('w+', find_speech_part, 'For A but not for B because neither C nor D'))
# coordinating conjunction A coordinating conjunction not coordinating conjunction B because neither C coordinating conjunction D

它改编自之前的答案。

最新更新