1

I want to get those lines that have strings from res list (at least 4 of them , o an O are substitute for zero), along with the names. With script below I get new lines without names, only if line has 0 and 1.

I have a text file with lines of names and numbers as below:

lines in txt file:

John Johns 1-1, 1-2
Adam Adams 1:0, 2:0
Dave Davis 1-0, 1:1
Jim Jims   1_0 1_1
Tim Tims 0 0 0 1
Tom Toms 2-0, 3:2
Pet Peters 1 0 1 1
Sam Sams 1.o 1.1
Ace Aces 10 11
Abe Abes 1O 11


res = ['1', '0', 'o', 'O', '1', '1']

with open('txt_file.txt') as oldfile, open('new_txt.txt', 'w') as newfile:
    for x in res:
        for line in oldfile:
            line_new = [x for x in res if (x in line)]
            line = ''.join(line_new)
            newfile.write(line)

Expected lines in new file

Dave Davis 1-0, 1:1
Jim Jims   1_0 1_1
Pet Peters 1 0 1 1
Sam Sams 1.o 1.1
Ace Aces 10 11
Abe Abes 1O 11
hoppdev
  • 19
  • 5

2 Answers2

0

I'm quite sure some threads already answer this question, since it's basically list to string matching.

you can already check this one : how-to-check-if-a-string-contains-an-element-from-a-list-in-python

or this one : check-list-of-words-in-another-string

Gwendal Yviquel
  • 382
  • 3
  • 13
0

Instead of using an ambiguous list, use the following concise approach based on specific regex pattern:

import re

with open('input.txt', 'r') as f_in, open('output.txt', 'w') as f_out:
    num_pat = re.compile(r'\b1[:.,_\s-]?[0oO],?\s+1[:.,_\s-]?1$')
    for line in f_in:
        if num_pat.search(line):
            f_out.write(line)

The final output.txt contents:

Dave Davis 1-0, 1:1
Jim Jims   1_0 1_1
Pet Peters 1 0 1 1
Sam Sams 1.o 1.1
Ace Aces 10 11
Abe Abes 1O 11
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • Can you please explain it shortly what does this line: \b1[:.,_\s-]?[0oO],?\s+1[:.,_\s-]?1$ and what if numbers in text file are others than 1 an 0 ? Thank you for your time! – hoppdev Oct 02 '19 at 13:15
  • @hoppdev, Honestly, for some time, the more I add my answers on SO - the more they get neglected and disregarded. I see a tendency of such "prejudice" – RomanPerekhrest Oct 02 '19 at 13:47
  • 1
    Thank you for pointing specific regex pattern to me, as a beginner I didn't have a slightest idea of this approach. At the end, after some learning, I manage to answer my other question with a simple line: 1.*?[0oO].*?1.*?1.*? – hoppdev Oct 06 '19 at 22:36