我想写一个函数,它接受一个文件名和一个列表作为参数,并读取相应文件中的文本,然后创建一个字典,其键是所提供列表的字符,值是这些字符的计数文本中的字符。如果文件不存在,则该函数返回一个空字典。 例如:
sample.txt
This is an example sentence
This is yet another sentence
这是我到目前为止编写的代码:
def text2dict(filename, characters):
count_word = dict()
for char in characters:
count_word[char] = 0
with open(filename) as input_text:
text = input_text.read()
words = text.lower().split()
for word in words:
_word = word.strip('.,:-)()')
if word in count_word:
count_word[_word] += 1
return count_word
file_name = "sample.txt"
list_char = ["a", "b", "c", "t"]
text2dict(file_name, list_char)
预期输出:
{'a':3, 'b':0, 'c':2, 't':6}
我得到的输出:
{'a': 0, 'b': 0, 'c': 0, 't': 0}
最佳答案
您可以为此使用 "".count()
。也不再需要预先填写字典,因为我们没有使用 iadd。
def text2dict(filename, characters):
count_letters = dict()
with open(filename) as input_text:
text = input_text.read()
for k in characters:
count_letters[k] = text.count(k)
return count_letters
有了这个你就得到了预期的结果
>>> file_name = r"sample.txt"
>>> list_char = ["a", "b", "c", "t"]
>>> print(text2dict(file_name, list_char))
{'a': 3, 'b': 0, 'c': 2, 't': 6}
关于python - 从文本文件中查找特定字符的出现 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67639086/