【问题标题】:How to read through a text file in python and count the number of times a certain character occurs in it?如何在python中读取文本文件并计算某个字符在其中出现的次数?
【发布时间】:2020-03-30 18:36:26
【问题描述】:

编程新手,学习python。 本周的重点是阅读 URL 文本文件。希望通读文本文件并计算字符“e”出现的次数。

import urllib.request
content = urllib.request.urlopen("https://www.gutenberg.org/files/2701/old/moby10b.txt")
content.read()
counter = 0
for 'e' in content:
    counter +=1
print(counter)

有什么建议吗?

【问题讨论】:

标签: python css text count


【解决方案1】:

如果您想读取 Internet 上的文件,请使用请求库向该地址发送请求。这会返回一个响应。 response.text 是网页的内容

试试这样:

import requests

response = requests.get("https://www.gutenberg.org/files/2701/old/moby10b.txt")

print(response.text.count("e"))

输出:

116960

【讨论】:

  • 我选择了这个 .import urllib.request fname = input('enter file') l = input('enter letter') counter = 0 content = urllib.request.urlopen(fname).read ().decode('utf-8') for letter in content: if(letter==l): counter+=1 print(counter)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-04
  • 2010-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-13
  • 2017-02-25
相关资源
最近更新 更多