1
該程序顯示出現在兩個文本文件上的單詞,且單詞只應包含字母。打印的信息將是單詞和頻率。
import re
from collections import OrderedDict
from operator import itemgetter
f = open('P1Input1.txt', 'r')
g = open('P1Input2.txt', 'r')
data = {}
data2 = {}
for line in f:
for word in line.split():
if word in data:
data[word] += 1
else:
if re.match("^[A-Za-z]*$", word):
data[word] = 1
f.close()
for line in g:
for word in line.split():
data2[word] = 1
g.close()
for key in data:
if key in data2:
data[key] += 1
else:
del data[key]
OrderedDict(sorted(data.items(), key = lambda t: t[1]))
print(data)
由於某些原因,值不斷變化,這裏是結果。我究竟做錯了什麼?
>>> ================================ RESTART ================================
>>>
{'is': 3, 'how': 2, 'hello': 5, 'it': 3, 'doing': 2, 'you': 2, 'a': 2, 'are': 2, 'day': 2, 'beautiful': 2}
>>> ================================ RESTART ================================
>>>
{'is': 3, 'hello': 5, 'beautiful': 2, 'are': 2, 'how': 2, 'a': 2, 'you': 2, 'it': 3, 'doing': 2, 'day': 2}
>>> ================================ RESTART ================================
>>>
{'hello': 5, 'a': 2, 'you': 2, 'are': 2, 'is': 3, 'it': 3, 'day': 2, 'beautiful': 2, 'how': 2, 'doing': 2}
>>>
你不是存儲'OrderedDict'任何地方。 –