在python的.txt文件中搜索字符串

2024-05-16 03:10:49 发布

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

所以我有一个叫做test的文件

But I must explain to you how all this mistaken idea of denounc ing pleasure and praising pain was born and I will give you a complet e account of the system, and expound the actual teachings of the great explo rer of the truth, the master-builder of human happiness. No one rejects, disli kes, or avoids pleasure itself, because it is pleasure, but because those who do no t know how to pursue pleasure rationally encounter consequences that are extremely painful . Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to ob tain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure tha t has no annoying consequences, or one who avoids a pain that produces no resultant pleasure

这段代码是用python编写的

with open('test.txt', 'r') as f:
    for line in f:
        line=line.strip()
        if 'trivial' in line:
            print(line)

但是,它不会打印任何内容,但是如果我将'trivial'替换为像“t”这样的字母,我将打印任何带有“t”的行。我做错什么了?你知道吗


Tags: orandofthetonoinis
1条回答
网友
1楼 · 发布于 2024-05-16 03:10:49

好的,我知道了。 只需要加上编码UTF16

with open("test.txt", "r", encoding="utf-16") as f:
    for line in f:
        if 'trivial' in line:
            print(line)

感觉糟透了

相关问题 更多 >