Python 搜索文件并找到精确匹配和打印行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15718068/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:45:43  来源:igfitidea点击:

Search File And Find Exact Match And Print Line?

pythonfilesearchmatch

提问by Robots

I searched around but i couldn't find any post to help me fix this problem, I found similar but i couldn't find any thing addressing this alone anyway.

我四处搜索,但找不到任何帖子来帮助我解决这个问题,我发现了类似的问题,但无论如何我都找不到任何单独解决此问题的方法。

Here's the the problem I have, I'm trying to have a python script search a text file, the text file has numbers in a list and every number corresponds to a line of text and if the raw_input match's the exact number in the text file it prints that whole line of text. so far It prints any line containing the the number.

这是我遇到的问题,我正在尝试让 python 脚本搜索文本文件,文本文件在列表中有数字,每个数字对应一行文本,如果 raw_input 匹配文本文件中的确切数字它打印整行文本。到目前为止,它打印包含数字的任何行。

Example of the problem, User types 20then the output is every thing containing a 2and a 0, so i get 220 foo200 baretc. How can i fix this so it just find "20"

问题的例子,用户输入20然后输出是包含 a2和 a 的所有东西0,所以我得到220 foo200 bar等等。我该如何解决这个问题,所以它只找到“20”

here is the code i have

这是我的代码

num = raw_input ("Type Number : ")
search = open("file.txt")
for line in search:
 if num in line:
  print line 

Thanks.

谢谢。

回答by unutbu

To check for an exactmatch you would use num == line. But linehas an end-of-line character \nor \r\nwhich will not be in numsince raw_inputstrips the trailing newline. So it may be convenient to remove all whitespace at the end of linewith

要检查完全匹配,您可以使用num == line. 但是line有一个行尾字符,\n或者因为去掉了尾随的换行符\r\n而不会出现。因此删除with末尾的所有空格可能会很方便numraw_inputline

line = line.rstrip()


with open("file.txt") as search:
    for line in search:
        line = line.rstrip()  # remove '\n' at end of line
        if num == line:
            print(line )

回答by naeg

The check has to be like this:

支票必须是这样的:

if num == line.split()[0]:

If file.txt has a layout like this:

如果 file.txt 有这样的布局:

1 foo
20 bar
30 20

We split up "1 foo"into ['1', 'foo']and just use the first item, which is the number.

我们分裂"1 foo"['1', 'foo'],只是使用的第一个项目,这是多少。

回答by Oni1

It's very easy:

这很容易:

numb = raw_input('Input Line: ')
fiIn = open('file.txt').readlines()
for lines in fiIn:
   if numb == lines[0]:
      print lines

回答by lenik

you should use regular expressions to find all you need:

你应该使用正则表达式来找到你需要的一切:

import re
p = re.compile(r'(\d+)')  # a pattern for a number

for line in file :
    if num in p.findall(line) :
        print line

regular expression will return you all numbers in a line as a list, for example:

正则表达式会将一行中的所有数字作为列表返回,例如:

>>> re.compile(r'(\d+)').findall('123kh234hi56h9234hj29kjh290')
['123', '234', '56', '9234', '29', '290']

so you don't match '200' or '220' for '20'.

所以你不匹配 '200' 或 '220' 为 '20'。

回答by Jetlef

num = raw_input ("Type Number : ")
search = open("file.txt","r")
for line in search.readlines():
    for digit in num:
        # Check if any of the digits provided by the user are in the line.
        if digit in line:
            print line
            continue

回答by The Aelfinn

Build lists of matched lines - several flavors:

构建匹配行的列表 - 几种风格:

def lines_that_equal(line_to_match, fp):
    return [line for line in fp if line == line_to_match]

def lines_that_contain(string, fp):
    return [line for line in fp if string in line]

def lines_that_start_with(string, fp):
    return [line for line in fp if line.startswith(string)]

def lines_that_end_with(string, fp):
    return [line for line in fp if line.endswith(string)]

Build generator of matched lines (memory efficient):

构建匹配行的生成器(内存效率高):

def generate_lines_that_equal(string, fp):
    for line in fp:
        if line == string:
            yield line

Print all matching lines (find all matches first, then print them):

打印所有匹配的行(首先找到所有匹配,然后打印它们):

with open("file.txt", "r") as fp:
    for line in lines_that_equal("my_string", fp):
        print line

Print all matching lines (print them lazily, as we find them)

打印所有匹配的行(在我们找到它们时懒惰地打印它们)

with open("file.txt", "r") as fp:
    for line in generate_lines_that_equal("my_string", fp):
        print line

Generators (produced by yield) are your friends, especially with large files that don't fit into memory.

生成器(由 yield生成)是您的朋友,尤其是对于不适合内存的大文件。