我想创建一个函数;
读取文本文件,逐字读取文件,并将这些字存储在数组中。
计算每个单词的出现次数,并且每个单词在数组中仅存储一次。
输出每个单词,并在其旁边显示其出现次数。
示例:
文本文件说:“弗兰克吃豌豆吃薯条豌豆”
将创建一个数组,[坦率,吃,豌豆,吃,薯条,豌豆]
然后,将打印最终产品;
坦率1吃2豌豆2薯条1
-
这是我到目前为止所拥有的
def countWordsInFile():
array = []
array2 = [1,2,3,4,5]
length = len(array)
fileName = getUserText("Enter the name of the file you want to read array from")
openFile = openNewFile(fileName,"read")
i = openFile
for words in i.read().split():
array.append(words)
print(array)
for i in range(0,length,1):
count = array.count[i]
array2.append(count)
print(array2)
您可以为此使用字典,更改后的代码如下:
def countWordsInFile():
array = []
array2 = [1,2,3,4,5]
length = len(array)
fileName = getUserText("Enter the name of the file you want to read array from")
openFile = openNewFile(fileName,"read")
i = openFile
for words in i.read().split():
array.append(words)
print(array)
words = {}
for word in array:
if word not in words:
words[word] = 1
else:
words[word] += 1
print(words)