2014-01-28 145 views
0

我試圖替換文檔中的所有四個字母單詞,並將其替換爲四個星號。該代碼可以識別四個字母的單詞,但無法替代它們。我做錯了什麼?嘗試使用'替換'函數來替換字符串中的某些單詞

這是我到目前爲止的代碼。

# wordfreq.py 
import string 

def compareItems((w1, c1),(w2,c2)): 
    if c1 >c2: 
     return -1 
    elif c1 == c2: 
     return cmp(w1, w2) 
    else : 
     return 1 


def main() : 
    print """This program analyzes word frequency in a file and 
      prints a report on the n most frequent words. \n """ 

    # get the sequence of words from the file 
    fname = raw_input("File to analyze: ") 
    text = open(fname, 'r').read() 
    text = str.lower(text) 
    for ch in '!"#$%&()*+,-./:;<=>[email protected][[\\]^_`{|}`' : 
     text = string.replace(text, ch, ' ') 
    words = string.split(text) 

    # construct a dictionary of word counts 
    counts = {} 
    for w in words : 
     if len(w) == 4: 
      w.replace("w", "\****",) 
    print words 


if __name__ == '__main__': main() 
+0

謝謝!這很好用! –

回答

1

str.replace()返回更新文本,您要更換"w",不是值的變量w。你並不需要在這裏使用str.replace();你有一個列表,你只需要用不同的字符串替換長度爲4的所有元素。

使用列表理解列表中的替換值:

words = ['****' if len(w) == 4 else w for w in words] 
print ' '.join(words)