gpt4 book ai didi

python - 改变Python中的字典/键

转载 作者:行者123 更新时间:2023-12-01 03:40:39 29 4
gpt4 key购买 nike

我已经在 Python 中运行了下面的代码,以从文本文件中生成单词列表及其计数。我该如何从“Frequency_list”变量中过滤掉计数为 1 的单词?

另外,如何将底部的打印语句循环导出到CSV

预先感谢您提供的任何帮助。

import re
import string
frequency = {}
document_text = open('Words.txt', 'r')
text_string = document_text.read().lower()
match_pattern = re.findall(r'\b[a-z]{3,15}\b', text_string)

for word in match_pattern:
count = frequency.get(word,0)
frequency[word] = count + 1

frequency_list = frequency.keys()



for words in frequency_list:
print (words, frequency[words])

最佳答案

要过滤掉单词,另一种方法是:

frequency = dict(filter(lambda (k,v): v>1, frequency.items())) 

要将底部的打印语句循环导出到 CSV,您可以这样做:

import csv    
frequency_list = ['word1','word2','word3'] # example

with open('output.csv','w') as csvfile:
writer = csv.writer(csvfile, delimiter=",")
writer.writerow(frequency_list)

这将生成一个“output.csv”文件,其中一行包含频率列表中的单词。

要为每个单词获取一行,请尝试以下操作:

with open('output.csv','w') as csvfile:
writer = csv.writer(csvfile, delimiter=",")
writer.writerows([i.strip() for i in l.split(',')] for l in frequency_list)

Update

要获取带有计数器的 csv,请保留您的初始字典并执行以下操作:

frequency = {"one":1,"two":2,"three":3} #example
with open('output.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
for key, value in frequency.items():
writer.writerow([key, value])

关于python - 改变Python中的字典/键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39692480/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com