python-3.x - 如何使用python计算文本文件中的特定字符?
问题描述
#Exercise 7: Counting...1...2...3...
#The purpose of this program is to ask a file from the user, open the file
# and counts the number of comma-separated values in it and report the result to the user
name_file = input("Enter name of file: ")
inf = open(name_file, "r")
count_comma = 0
line = inf.readline()
for char in line:
if "," in char:
count_comma +=1
print (count_comma)
inf.close()
当我运行它时打印 0。为什么?
解决方案
你可能会更好
count_comma = len(line.split(","))
但你必须运行 timeit 才能确定
推荐阅读
- javascript - 使用lookbehind忽略两个匹配项之间的字符串,但无论如何都要捕获它
- java - 如何使用 SSL/SSH 工作示例连接 SecureAS400
- web3 - 信任钱包 dapp 连接并签名传输消息
- wordpress - WP_User_Query 中断并忽略它下面的所有代码
- security - 隐藏从后端获取的用户数据
- neo4j - 在 neo4j 中获取可选数据的最快方法
- youtube - 如何通过 v3 API 检测 youtube 视频是否包含付费推广
- javascript - Javascript加入不适用于创建的数组
- python - Python,使用相对路径导入的模拟
- reactjs - React 中的上传列表状态管理