我是一个初学者,我正在努力做到以下几点。我需要从一个网页中打开一个文本文件,其中包含一个如下所示的小列表。
我需要做的是计算有多少个大M字母和多少个不同的字母(这里是3 M,F和C)并将其打印出来。然后我需要创建一个新的文本文件并将(仅)所有名称传输到其中并将其保存在我的硬盘上。到目前为止,我只想出了如何从网页打开列表。
import urllib.request
url = 'http://mypage.com/python/textfile.txt'
with urllib.request.urlopen(url) as myfile:
for i in myfile:
i = i.decode("ISO-8859-1")
print(i,end=" ")
但这就是我所知道的。我尝试使用count()但它当时只计算一行,它计算一行(1)中有多少个大M个字母,但它不会将它们加在一起用于整个文本(3)。任何帮助将不胜感激,谢谢。
答案 0 :(得分:0)
我不确切知道你在做什么,但试试这个:
import urllib.request
url = 'http://mypage.com/python/textfile.txt'
with urllib.request.urlopen(url) as myfile:
number_of_M = 0
set_of_big_letters = set()
for i in myfile:
i = i.decode("ISO-8859-1")
name, lastname, big_letter, _ = i.split(' ') # if they are seperated by space
set_of_big_letters.add(big_letter)
if big_letter == 'M':
number_of_M += 1
print(number_of_M)
print(len(set_of_big_letters))