2024-09-29 21:46:25 发布
网友
我不确定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
以下对代码的轻微编辑将允许您计算由file_url定义的文件中由参数word定义的任何单词。你知道吗
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做任何事了。相反,您需要:
words
if line[1:] == 'the raven':
检查整行,减去第一个字符,是否就是“乌鸦”。你知道吗
(为处理unicode/字节而编辑):如果您想合计“the raven”在整个文件中出现的总次数,可以跳过split和if,直接从每一行获取出现次数。因为请求为您提供bytes对象(在Python3中)或unicode对象(在Python2中),所以您需要首先使用适当的编码对行进行解码:
split
if
bytes
unicode
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
根据数据源的不同,您可能需要选择不同的编码。你知道吗
以下对代码的轻微编辑将允许您计算由
file_url
定义的文件中由参数word
定义的任何单词。你知道吗当你这么做的时候
您正在为变量
words
分配一个字符串列表-行中的非空白字符串。但在那之后你就再也不能用words
做任何事了。相反,您需要:检查整行,减去第一个字符,是否就是“乌鸦”。你知道吗
(为处理unicode/字节而编辑):如果您想合计“the raven”在整个文件中出现的总次数,可以跳过
split
和if
,直接从每一行获取出现次数。因为请求为您提供bytes
对象(在Python3中)或unicode
对象(在Python2中),所以您需要首先使用适当的编码对行进行解码:如果要返回“the raven”出现的行总数,可以执行以下操作:
根据数据源的不同,您可能需要选择不同的编码。你知道吗
相关问题 更多 >
编程相关推荐