如何计算以单词''开头的行数。在python中

时间:2018-01-29 21:03:05

标签: python file-io

我试图获得以&#34开头的行数;"在文件中

def count_the(file_url):
    r = requests.get(file_url, stream=True)
    pat = re.search(r'^the', file_url)
    count = 0
    for line in r.iter_lines():
        if line.startswith('the'):`
            return count += 1

2 个答案:

答案 0 :(得分:1)

您将退货放在了错误的位置,并且您也可以避免使用re.search

def count_the(file_url):
    r = requests.get(file_url, stream=True)
    count = 0
    for line in r.iter_lines():
        if line.startwith('the'):
            count += 1
    return count

答案 1 :(得分:0)

您的代码存在一些严重缺陷:

def count_the(file_url):
    r = requests.get(file_url, stream=True)
    count = 0
    for line in r.iter_lines():
        if line.startswith('the'):`
            count += 1
    return count
  1. 删除pat
  2. 首先计算,然后在循环外return count