需要以下功能: 一個文本檔案,需要讀入 Python,并且必須按字母順序對單詞進行排序,作為輸出到字典中。
給定的文本檔案:
Im about to go to the movies on Monday!
And Im very excited to go.
以下代碼讀取檔案并洗掉不必要的字符:
def movietext():
with open("movietext.txt", "r") as textfile:
text = textfile.read()
for char in "!":
text=text.replace(char,"")
return text
print(movietext())
結果如下:
Im about to go to the movies on Monday
And Im very excited to go
這樣做的要求是列印出如下的字典:
And: 1
about: 1
excited: 1
go: 1
Im: 2
Monday: 1
movies: 1
on: 1
the: 1
to: 3
very: 1
非常感謝您對解決此問題的任何幫助。
uj5u.com熱心網友回復:
您可以使用一些 Python 的內置函式sorted()、zip()和map():
string = '''Im about to go to the movies on Monday
And Im very excited to go'''
words = string.split()
words2 = sorted(set(words))
for key, value in zip(words2, map(words.count, words2)):
print(f"{key}: {value}")
輸出:
And: 1
about: 1
excited: 1
go: 1
Im: 2
Monday: 1
movies: 1
on: 1
the: 1
to: 3
very: 1
解釋:
如您所知,words = string.split()獲取字串string并將每個由空格分隔的子字串存盤到 list 中words。
線
words2 = sorted(set(words))
洗掉所有重復的單詞,對它們進行排序,并將結果串列存盤到變數中words2。
最后,線
zip(words2, map(words.count, words2))
將排序串列中的每個單詞映射到list.count()方法(其中串列是包含重復單詞的原始串列),并列印出它們對應單詞旁邊的計數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358182.html
