简体   繁体   中英

how to find specific digit values in a text file of one column?

for line in fname:
    fields = line.rstrip("\n").split()
    dc = refindall('0.8|0.9).group()
    samples = line
   sys.stdout.writelines(samples)

I got another problem with finding a specific float(digit ( 0.8 and 0.9) value in each line of one column text file. Secondly, if it finds this line, it should be deleted. Here is my code:

You have a number of errors in your code:

  • There is a missing dot between re and findall.
  • The dot in the regular expression means "match any character".
  • Your string is not terminated correctly because there is a missing quote.
  • re.findall takes two parameters. You seem to be providing only one.
  • re.findall returns a list of strings. A list doesn't have a method called 'group'.
  • The code is not indented correctly.

However there's no need for regular expressions here. Try this list comprehension instead:

lines = [line for line in lines if not (line == '0.8' or line == '0.9')]
for line in fname:
 fields = line.rstrip("\n").split()
dc = re.findall(r'0\.8|0\.9').group()
samples = line

sys.stdout.writelines(samples)

I think you weren't escaping the . in the regex.

EDIT: See Mark Byers post: You really do not need regexes for something like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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