python - 从文本文件中查找特定字符的出现 - Python

标签 python python-3.x

我想写一个函数,它接受一个文件名和一个列表作为参数,并读取相应文件中的文本,然后创建一个字典,其键是所提供列表的字符,值是这些字符的计数文本中的字符。如果文件不存在,则该函数返回一个空字典。 例如:

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/

相关文章:

python - 代码在空闲状态下工作,但在 VS Code 中出现错误

python - 当值与另一列匹配时回填 Pandas 系列中的值

python - 正则表达式数字之间的整个字符串匹配

python - 如何在 python 中获取数学函数作为输出

python - 值错误 : invalid literal for int() with base 10: '1000.00'

python - 根据条件返回列名

python - 将尾随字符替换为另一个字符

python - PyCharm 调试变量 View : disabling variable address

python - 在argparse中使用 '--help'命令

python - 将 TimedeltaIndex 转换为 DatetimeIndex