2014-11-20 55 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'