【问题标题】:file handling + word scraping (trying to find all the words in a file that end with 'y')文件处理 + 单词抓取(尝试查找文件中以 'y' 结尾的所有单词)
【发布时间】:2021-06-17 16:35:50
【问题描述】:

错误:回溯(最近一次调用最后一次):文件“c:\Users\Pranjal\Desktop\tstp\zen_scraper.py”,第 5 行,用文字表示 = re.findall("$y",file) File " C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2288.0_x64__qbz5n2kfra8p0\lib\re.py",第 241 行,在 findall return _compile(pattern, flags).findall(string) TypeError: expected string or bytes-like object PS C:\Users\Pranjal\Desktop\tstp>

import re

file = open("zen.txt",'r')

words = re.findall("$y",file)
print(words)

【问题讨论】:

    标签: python web-scraping file-handling pdf-scraping


    【解决方案1】:

    您已打开文件,但尚未获得其内容。 另外,这里不需要re,只需str.endswith()即可。

    with open("zen.txt",'r') as f:
        for line in f:
            for word in line.split():
                if word.endswith('y'):
                    print(word)
    

    【讨论】:

    猜你喜欢
    • 2021-12-13
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多