Python-将键值保存到文件中



我有下面这样的代码,它检查列表中的每个文件,并返回单词+数量(即文件中找到的记录数量(。我希望这个结果被覆盖到以前打开的文件中,并保存代码中的结果。

不幸的是,我对此有意见。

我有文件,我有数据如下:

abc
cds
cds
abf

以下代码作为结果给出:

abc : 1
cds : 2
abf : 1

我想覆盖我的文件并将结果代码写入文件:

import os
import re

folderPath = r'C:/Users/adm/test'

if os.path.exists(folderPath):
files = []
for name in os.listdir(folderPath):
if os.path.isfile(os.path.join(folderPath, name)):
files.append(os.path.join(folderPath, name))
for ii in files:
with open(ii, "r") as f:
# Create an empty dictionary
d = dict()
# Loop through each line of the file
for line in f:
# Remove the leading spaces and newline character
line = line.strip()
# Convert the characters in line to
# lowercase to avoid case mismatch
line = line.lower()
# Split the line into words
words = line.split(" ")
# Iterate over each word in line
for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
with open(ii, "w") as outfile:
# # Print the contents of dictionary
for key in list(d.keys()):
n = print(key, ":", d[key])
outfile.write('%s:%sn' % key, str(d[key]))

最初"blankpaper.txt";是

abc
cds
cds
abf

在应用下面的代码之后;blankpaper.txt";成为(按要求(

abc : 1
cds : 2
abf : 1

根据要求,我改写了原始文件。然而,我建议(1(在覆盖原始文件之前先复制它;(2(如果输入不一致,则由于解析文件而写入另一个文件并不完美。分析文件采用输入中的特定格式,如果将来得到类似但不同的输入,相同的代码可能不起作用,如果不首先复制原始文件而直接覆盖原始文件,则可能会丢失原始文件中的数据。

我希望这能有所帮助。如果有任何问题,或者这不是你想要的,请告诉我!

# dictionary storing unique words and counts
words = {}
# r+ opens file for both reading and writing
with open("blankpaper.txt", 'r+') as f:
# read file and count words
for line in f:
# assuming one line = one word
word = line.strip()
if word in words:
words[word] += 1
else:
words[word] = 1
# clear file
f.seek(0)
f.truncate()
# write to the file
for key in words:
f.write(f"{key} : {words[key]}n")
print(words) # -> {'abc': 1, 'cds': 2, 'abf': 1}

最新更新