gpt4 book ai didi

Python3 - 增加文本文件内的数字

转载 作者:行者123 更新时间:2023-12-01 07:54:50 25 4
gpt4 key购买 nike

我有以下文本文件,其结构如下:word count

product 5
order 4
tracking 1

这意味着单词product在输入文档中被发现5次。

我有一个名为 WordFrequency.py 的脚本,用于查找单词以及它们在输入文件中出现的次数:

import re
from collections import Counter

def count_words(file_path):
with open("/Users/oliverbusk/Sites/Sandbox/storage/app/" + file_path, 'r', encoding="utf-8") as f:

matches = re.findall(r'\b[a-zA-Z]{3,}\b', f.read())

wordcount = Counter(matches)

for word in wordcount:
string = word + " " + str(wordcount[word])
write_to_file(string)

def write_to_file(word):
with open("/Dictionaries/eng.txt", "a+") as f:
f.write(word + "\n")

基本上,上面将读取输入文件file_path,并将单词和计数添加到eng.txt

但是,每当我运行它时,结果都会附加到 eng.txt 文件中,例如:

product 5
order 4
tracking 1
product 5
order 4
tracking 1

相反,如果该单词已存在于 eng.txt 文件中,我希望它增加 count

最佳答案

一种方法是首先读取文件的内容,然后递增计数。

例如:

import re
from collections import Counter, defaultdict

def count_words():
#Read Content#
with open("/Dictionaries/eng.txt", "r") as f:
data = defaultdict(int)
for line in f:
key, value = line.strip().split()
data[key] = int(value)

with open("/Users/oliverbusk/Sites/Sandbox/storage/app/" + file_path, 'r', encoding="utf-8") as f:
matches = re.findall(r'\b[a-zA-Z]{3,}\b', f.read())
wordcount = Counter(matches)
for word, count in wordcount.items():
data[word] += count #Increment Count

#Write To File
write_to_file(data)

def write_to_file(data):
with open("/Dictionaries/eng.txt", "w") as f:
for word, count in data.items():
string = word + " " + str(count)
f.write(string + "\n")

关于Python3 - 增加文本文件内的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56036269/

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