[英]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. 我正在尝试编写一个程序,该程序采用文本文件并通过使用.split方法将其拆分来解释每一行。
I am trying to split up a line that looks like this: 4-Jan-72 followed by a tab and then a float. 我正在尝试拆分如下所示的行:72年1月4日,接着是制表符,然后是浮点数。 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.
有人告诉我使用'\\ t'拆分选项卡,但是我不确定如何在一行中同时使用这两个选项卡。
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, 输入文件
file.txt
包含,
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.