计算文件中的特定字符(Python) [英] Counting specific characters in a file (Python)
问题描述
我想计算文件中的特定内容,即 "--undefined--"
出现的次数.这是文件的一部分内容:
I'd like to count specific things from a file, i.e. how many times "--undefined--"
appears. Here is a piece of the file's content:
"jo:ns 76.434
pRE 75.417
zi: 75.178
dEnt --undefined--
ba --undefined--
我尝试使用这样的东西.但它不起作用:
I tried to use something like this. But it won't work:
with open("v3.txt", 'r') as infile:
data = infile.readlines().decode("UTF-8")
count = 0
for i in data:
if i.endswith("--undefined--"):
count += 1
print count
我是否必须实现元组字典来解决这个问题,或者有更简单的解决方案吗?
Do I have to implement, say, dictionary of tuples to tackle this or there is an easier solution for that?
有问题的单词在一行中只出现一次.
The word in question appears only once in a line.
推荐答案
readlines()
返回行列表,但它们没有被剥离(即它们包含换行符).要么先剥离它们:
readlines()
returns the list of lines, but they are not stripped (ie. they contain the newline character).
Either strip them first:
data = [line.strip() for line in data]
或检查 --undefined--\n
:
if line.endswith("--undefined--\n"):
或者,考虑字符串的 .count()
方法:
Alternatively, consider string's .count()
method:
file_contents.count("--undefined--")
这篇关于计算文件中的特定字符(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!