文件处理 + 单词抓取(试图找到文件中以 'y' 结尾的所有单词)

file handling + word scraping (trying to find all the words in a file that end with 'y')

错误:回溯(最近调用最后一次):文件“c:\Users\Pranjal\Desktop\tstp\zen_scraper.py”,第 5 行,换句话说 = re.findall(“$y”,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) 类型错误:预期的字符串或类字节对象 PS C:\Users\Pranjal\Desktop\tstp>

import re

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

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

您已打开文件,但尚未获取其内容。 此外,这里不需要 restr.endswith() 就足够了。

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