如何将两个字典写入输出文件"txt"



这实际上是一个由 4 部分组成的问题:

1( 返回一个字典,每个键是单词长度,其值是具有该长度的单词数。 例如,如果输入文件的文本是"Hello Python people Welcome to the world of Python",那么字典应该是: {2: 2, 3: 1, 5: 2, 6: 3, 7: 1}

2( 返回一个字典,每个键都是一个单词,其值是该单词的出现次数。 例如 {'hello': 1, 'of': 1, 'people': 1, 'python': 2, 'the': 1, 'to': 1,"欢迎":1,"世界":1}

我已经使用以下代码完成了前两部分。

def make_length_wordcount(x):
filename=x+'.txt'
infile=open(filename)
wordlist=infile.read().split()
counter1={}
for word in wordlist:
if len(word) in counter1:
counter1[len(word)]+=1
else:
counter1[len(word)]=1
infile.close()
print(counter1)
def make_word_count(string):
words=string.lower().split()
dictionary={}
for word in words:
dictionaryp[word]=0
for word in words:
dictionary[word]+=1
print(dictionary) 

我无法弄清楚如何做第 3 部分(和 4(:

3(使用上述两个函数 -make_length_wordcount()make_word_count()- 构建(i(长度字数字典和(ii(字数字典。

打开一个新的输出文件"FILE_analyzed_FIRST_LAST.txt"并将两个词典写入此文件(格式如下(。 输出文件名为"test_analyzed_HYUN_KANG.txt",它应包含以下行:

Words of length 2 : 2
Words of length 3 : 1
Words of length 5 : 2
Words of length 6 : 3
Words of length 7 : 1
to : 1
of : 1
people : 1
the : 1
python : 2
welcome : 1
hello : 1
world : 1

4( 在"hw2_FIRST_LAST.py"文件中,使用以下输入运行 analyze_text(( 函数三次:a. "nasdaq.txt"b. "raven.txt"c. "frankenstein.txt"

hw2.py 代码应生成以下三个文件:"nasdaq_analyzed_FIRST_LAST.txt""raven_analyzed_FIRST_LAST.txt""frankenstein_analyzed_FIRST_LAST.txt"

我的老师并没有真正教我们任何关于编写文件的知识,所以这让我非常困惑。

首先要做几件事: 1(您可以避免

if len(word) in counter1:
counter1[len(word)]+=1
else:
counter1[len(word)]=1

通过使用集合模块中的默认字典或计数器:

counter1 = defaultdict(int)
for word in wordlist:
counter1[word] += 1

这同样适用于make_word_count

def make_word_count(string):
words = string.lower().split()
dictionary = Counter(words)
print(dictionary.most_common(10))

对于您的第三点(我没有测试,但您明白了(:

def make_text_wordlen(counter1):
text = ''
for wordlen, value in counter1.items():
text += f'Words of length {wordlen} : {value}n'
with open('your_file.txt', 'w') as f:
f.write(text)
def make_text_wordcount(dictionary):
text = ''
for word, count in dictionary.items():
text += f'{word} : {count}n'
with open('your_file.txt', 'a') as f:  # 'a' parameter to append to existing file
f.write(text)

我会让你弄清楚第四点。

最新更新