需要以下函数:一个文本文件,需要读入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
非常感谢您为解决这一问题提供的任何帮助。
您可以使用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
,并将用空格分隔的每个子字符串存储到列表words
中。
线路
words2 = sorted(set(words))
删除任何重复的单词,对它们进行排序,并将结果列表存储到变量words2
中。
最后,线路
zip(words2, map(words.count, words2))
将排序列表中的每个单词映射到list.count()
方法(其中列表是包含重复单词的原始列表(,并打印出其对应单词旁边的计数。