【问题标题】:Python word in file change文件更改中的 Python 单词
【发布时间】:2015-01-18 17:13:21
【问题描述】:

我正在尝试将文本中的名词单词更改为“名词”。 我遇到了麻烦。这是我目前所拥有的。

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 

有什么想法吗?

【问题讨论】:

  • “我遇到了麻烦”并不能很好地描述您的问题。究竟是什么问题?

标签: python list replace split


【解决方案1】:

你的切片是空的:

>>> 'somethingion'[-1:-3]
''

因为终点位于起点之前。你可以在这里使用[-3:]

>>> 'somethingion'[-3:]
'ion'

但你最好使用str.endswith() 代替:

ch.endswith(("ion", "ism", "ity"))

如果字符串以 3 个给定字符串中的任何一个结尾,该函数将返回 True

并不是ch实际上是一个词;如果word 是一个字符串,那么for ch in word 会遍历单个字符,这些字符永远不会以3 个字符的字符串结尾,它们本身只有一个字符长。

您查看下一个和上一个单词的尝试也会失败;您不能将列表或文件对象用作可调用对象,更不用说将file(word - 1) 用作有意义的表达式(字符串- 1 失败,以及file(...))。

您可以在这里使用正则表达式,而不是循环遍历“单词”:

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)

这会查找以您的三个子字符串结尾的单词,但前提是前面有 the,后面是 ofon,并用 noun 替换它们。

演示:

>>> 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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 2019-03-26
    • 2017-01-10
    相关资源
    最近更新 更多