简体   繁体   中英

Splitting a list from a text file in more than one way

I am trying to write a program that takes a text file and interprets each line in chunks by splitting it using the .split method.

I am trying to split up a line that looks like this: 4-Jan-72 followed by a tab and then a float. I want to try and split it so the '-' and tab are gone. I was told to use '\\t'to split the tab but I'm not sure how to use both with one line.

line = rain_file.readline().strip().split("-",'\t')

I currently get this as my error.

line = rain_file.readline().strip().split("-",'\t')
TypeError: 'str' object cannot be interpreted as an integer

Seems like you want something like this,

Input file file.txt contains,

foo
4-Jan-72    10.5678
bar

Code:

#!/usr/bin/python3
import re
with open('file.txt', 'r') as f:
    for line in f:
        if re.match(r'\d+-[A-Z][a-z]+-\d+\b', line):
            line = re.sub(r'\t.*|-', r'', line)
            print(line, end='')
        else:
            print(line, end='')

Output:

foo
4Jan72
bar

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