从网络计算单词

2024-03-29 10:42:27 发布

您现在位置:Python中文网/ 问答频道 /正文

更新(我需要重新措辞)

我正在努力做到以下几点:

编写一个程序,下载并计算http://data.pr4e.org/romeo.txt'.

然而,我不知道该怎么做。我有以下工作代码:


fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
for line in fhand:
    print(line.decode().strip())

以上将下载4行。我需要能够下载它,以及获得33的计数

是否有一种方法可以在代码中同时执行这两项任务?我的教授告诉我:

import urllib.parse, urllib.request, urllib.error
import re



url = "http://data.pr4e.org/romeo.txt"

我觉得有一个线索,我必须使用re,但不知道如何应用它来解决这个问题


Tags: 代码orgimport程序retxthttpdata
2条回答

另一种使用容器数据类型计数器https://docs.python.org/3/library/collections.html

import urllib.request
from collections import Counter
with urllib.request.urlopen('http://data.pr4e.org/romeo.txt') as response:
    words = response.read().decode('utf-8').split()
c = Counter(words)
# optionally
print(c.most_common())

您所做的是计算每个单词出现的次数,当您使用.split()方法时,您可以将每行中显示的项目数相加,如下所示:

counts = 0
for line in fhand.readlines():
    words = line.decode().split()
    counts += len(words)

print(counts)

相关问题 更多 >