如何计算一个词有多少行

2024-09-29 21:46:25 发布

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

我不确定if语句是否错误?我试着分割每一行,遍历每一个索引,找到“渡鸦”并返回计数。你知道吗

def count_word(file_url, word):
    r = requests.get(file_url, stream=True)
    count = 0

    for line in r.iter_lines():
        words = line.split()
        if line[1:] == 'the raven':
            count += 1
    return count

Tags: trueurlstreamgetifdefcount错误
2条回答

以下对代码的轻微编辑将允许您计算由file_url定义的文件中由参数word定义的任何单词。你知道吗

def count_word(file_url, word):
    r = requests.get(file_url, stream=True)
    count = 0

    for line in r.iter_lines():
        count += line.count(word)

    return count

当你这么做的时候

`words = line.split()`

您正在为变量words分配一个字符串列表-行中的非空白字符串。但在那之后你就再也不能用words做任何事了。相反,您需要:

if line[1:] == 'the raven':

检查整行,减去第一个字符,是否就是“乌鸦”。你知道吗

(为处理unicode/字节而编辑):如果您想合计“the raven”在整个文件中出现的总次数,可以跳过splitif,直接从每一行获取出现次数。因为请求为您提供bytes对象(在Python3中)或unicode对象(在Python2中),所以您需要首先使用适当的编码对行进行解码:

for line in r.iter_lines():
    count += line.decode('utf-8').count('the raven')

如果要返回“the raven”出现的行总数,可以执行以下操作:

for line in r.iter_lines():
    if 'the raven' in line.decode('utf-8'):
        count += 1

根据数据源的不同,您可能需要选择不同的编码。你知道吗

相关问题 更多 >

    热门问题