文件更改中的Python word
我试图将文本中的名词改为“名词”。 我有麻烦了。这是我到目前为止所拥有的文件更改中的Python word,python,list,replace,split,Python,List,Replace,Split,我试图将文本中的名词改为“名词”。 我有麻烦了。这是我到目前为止所拥有的 def noun(file): for word in file: for ch in word: if ch[-1:-3] == "ion" or ch[-1:-3] == "ism" or ch[-1:-3] == "ity": word = "noun" if file(word-1) == "the" and (file
def noun(file):
for word in file:
for ch in word:
if ch[-1:-3] == "ion" or ch[-1:-3] == "ism" or ch[-1:-3] == "ity":
word = "noun"
if file(word-1) == "the" and (file(word+1)=="of" or file(word+1) == "on"
word = "noun"
# words that appear after the
return outfile
有什么想法吗?您的切片是空的:
>>> 'somethingion'[-1:-3]
''
因为端点位于起点之前。您可以在这里使用[-3::
:
>>> 'somethingion'[-3:]
'ion'
但您最好使用以下选项:
如果字符串以3个给定字符串中的任何一个结尾,函数将返回True
并不是说ch
实际上是一个词;如果word
是一个字符串,那么forch-in-word
将迭代各个字符,这些字符永远不会以3个字符的字符串结束,因为它们本身只有一个字符长
你想看下一个和前一个单词的尝试也会失败;不能将列表或文件对象用作可调用对象,更不用说将文件(word-1)
用作有意义的表达式(字符串-1
失败,以及文件(…)
)
您可以在此处使用正则表达式,而不是在“word”上循环:
import re
nouns = re.compile(r'(?<=\bthe\b)(\s*\w+(?:ion|ism|ity)\s*)(?=\b(?:of|on)\b)')
some_text = nouns.sub(' noun ', some_text)
“我有麻烦了”并不能很好地描述你的问题。究竟是什么问题?
import re
nouns = re.compile(r'(?<=\bthe\b)(\s*\w+(?:ion|ism|ity)\s*)(?=\b(?:of|on)\b)')
some_text = nouns.sub(' noun ', some_text)
>>> import re
>>> nouns = re.compile(r'(?<=\bthe\b)(\s*\w+(?:ion|ism|ity)\s*)(?=\b(?:of|on)\b)')
>>> nouns.sub(' noun ', 'the scion on the prism of doom')
'the noun on the noun of doom'