2014-11-20 52 views
-2

我正在尝试将文本中名词中的单词改为“名词”。 我有麻烦。这是我到目前为止。Python中的文件更改

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 

任何想法?

+3

“我有麻烦”是不是很描述你的问题。究竟是什么问题? – iCodez 2014-11-20 18:01:20

回答

0

你的片都是空的:

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

因为端点位于开始之前。你可以只使用[-3:]这里:

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

但你会使用str.endswith(),而不是更好:如果字符串与任何给定的3个字符串的结束

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

该函数将返回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'