How to search for word in text file and print part of line with Python?

后端 未结 2 1164
南旧
南旧 2021-01-14 15:21

I\'m writing a Python script. I need to search a text file for a word and then print part of that line. My problem is that the word will not be an exact match in the text fi

相关标签:
2条回答
  • 2021-01-14 15:46

    Well, it may not be much, but you could always use regex:

    m = re.search(r'(color\=.+?(?= )|color\=.+?$)', line)
    if m:
        text = m.group() # Matched text here
    
    0 讨论(0)
  • 2021-01-14 15:51

    Here's one way - split each line by spaces, then search each part for "color=":

    with open("textfile.txt") as openfile:
        for line in openfile:
            for part in line.split():
                if "color=" in part:
                    print part
    
    0 讨论(0)
提交回复
热议问题