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()
謝謝!這很好用! –