【问题标题】:How to replace different phrases with one word - python [duplicate]如何用一个词替换不同的短语 - python [重复]
【发布时间】:2017-08-19 11:18:10
【问题描述】:

在学习 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")

如果我使用输入“name1 for name2”运行它。输出是“name1 协调连词 name2” 但是以“name1 and name2”作为输入,它会打印“name1 and 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”。有没有办法在不使用一堆 if 语句的情况下将变量 coorcon 中的所有单词替换为“并列连词”?提前致谢。

【问题讨论】:

  • 简而言之:re.sub 可能是最简单的方法,我建议您尝试打印coordconj 的值,因为or 不会做任何接近您认为的事情是的。
  • 刷新页面。链接位于标题和正文之间。
  • 我可以帮助你一点,让你知道你的表达 "for" or "and" or "nor" ... 是有效的,但不是你想要的。相反,您正在执行逻辑操作,并且由于short-cicruit logic,将返回第一个字符串。也就是说,您的逻辑表达式的计算结果仅为“for”。

标签: python python-2.7 replace


【解决方案1】:
"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

改编自previous answer

【讨论】:

  • 我明白了,我会试试别的。谢谢
  • 真的没有必要像这样回答常见的重复 - 你甚至没有提供解决方案。这更适合作为评论。
  • 还有真的不需要复制已有的答案。
  • 所有原件都会对 OP 有所帮助。这就是我把它们放在那里的原因。如果 OP 不理解这些答案中使用的某些术语,他们应该研究它们,而不是等待与他们一样有可能将此站点用作编码服务的其他人。
  • 当我找到对你的帖子投了反对票的匿名用户时,我会通知他们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多