简体   繁体   English

在.txt文件中查找特定文本

[英]Looking for a specific text in .txt file

I am new at Python and for a simple project I tried to make a simple program using .txt file. 我是Python新手,对于一个简单的项目,我尝试使用.txt文件制作一个简单的程序。

A sample text file looks like this: 示例文本文件如下所示:

Name = Garry
Age = 20

Then, I wrote this 然后,我写了这个

Search = input("Whose age do you want to know? ")

    f = open("text exe.txt", "r")
    reviews = f.readlines()
    this_line = reviews[0].split(" = ")
    if this_line[1] == Search:
        print("yes")
    f.close()

When I tried to input "Garry" into Search, "yes" doesn`t come out. 当我尝试在搜索中输入“加里”时,“是”不会出现。 Does anyone know the reason? 有人知道原因吗? Thank you 谢谢

Welcome! 欢迎! Comparing strings can be very tricky: this_line[1] contains not only "Garry", but also e line separator "\\r\\n". 比较字符串可能非常棘手: this_line[1]不仅包含“ Garry”,还包含e行分隔符“ \\ r \\ n”。

Although "Garry" (your input) and "Garry\\r\\n" (from your file) appear the same to us, they are considered different by == operator. 尽管“ Garry”(您的输入)和“ Garry \\ r \\ n”(来自您的文件)在我们看来是相同的,但==运算符将它们视为不同。

The solution below removes spaces and other non-visible characters around the word, producing the desired output: 下面的解决方案删除单词周围的空格和其他不可见字符,从而产生所需的输出:

Search = input("Whose age do you want to know? ")

f = open("text exe.txt", "r")
reviews = f.readlines()
this_line = reviews[0].split(" = ")
if this_line[1].strip() == Search.strip():
    print("yes")
f.close()

This could solve your problem. 这样可以解决您的问题。

Search = input("Whose age do you want to know? ")
f = open("test.txt", "r")
reviews = f.readlines()
reviews = [x.strip() for x in reviews] 
# print(reviews)
this_line = reviews[0].split(" = ")
if this_line[1] == Search:
    print("yes")
    f.close()

In the txt file the lines are separated with a \\n . 在txt文件中,行用\\n分隔。 If you print this_line it will be ['Name = Gary\\n', 'Age = 20\\n'] . 如果打印this_line ,它将为['Name = Gary\\n', 'Age = 20\\n'] So you should replace the "\\n" with a empty sting. 因此,您应该用空字符串替换“ \\ n”。 if this_line[1].replace("\\n","") == Search: will work. if this_line[1].replace("\\n","") == Search:将起作用。

Why deal with lists , splits and loops when you can do it this way? 如果可以通过这种方式处理列表,拆分和循环,为什么要这样做呢? You'll deal with that plenty when learning python, in the meantime, here's a nice clean solution: 在学习python的同时,您会处理大量的工作,同时,这是一个不错的干净解决方案:

search = input('Enter:')
f = open("text exe.txt", "r")
if search in f.read():
    print('Yes')
else:
    print('No')
f.close()

Try this 尝试这个

_INPUT_FILE = 'input.txt'

_OUTPUT_FILE = 'output.txt'

def main(): 

pattern = re.compile('^(.*)' +re.escape(sys.argv[1]) + '(.*)$') 

o = open(_OUTPUT_FILE, 'w') 

with open(_INPUT_FILE) as f: 

for line in f: 

match = pattern.match(line) 

if match is not None: 

o.write(match.group(1) + match.group(2) + os.linesep)

o.close() 

if __name__ == '__main__': 

main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM