奇怪的分隔符
Weird Delimiter
在 Python 中,我试图解析一个文件并分隔值,但是,我正在使用一个奇怪的分隔符。有人可以帮忙吗?谢谢!
我正在解析的文件中的行类似于:
john-burk AL
john-smith CA
john-joe FL
john-john TX
当前代码:
with open('info.txt', 'r') as f:
for line in f:
try:
name, state = line.split(<do not know what to use>)
except Exception as e:
print "[-] Error parsing data " + str(e)
预期输出:
name = "john-burk"
state = "AL"
引用 str.split
文档,
str.split([sep[, maxsplit]])
If sep is not specified or is None
, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
所以,你可以简单地做
name, state = line.split()
print name, state
由于我们没有指定分隔符,所以Python将根据任意数量的连续空白字符作为分隔符进行分割。因此,您的数据可以分为 name
和 state
注意: 如果 name
有任何空白字符,这将不起作用。
在 Python 中,我试图解析一个文件并分隔值,但是,我正在使用一个奇怪的分隔符。有人可以帮忙吗?谢谢!
我正在解析的文件中的行类似于:
john-burk AL
john-smith CA
john-joe FL
john-john TX
当前代码:
with open('info.txt', 'r') as f:
for line in f:
try:
name, state = line.split(<do not know what to use>)
except Exception as e:
print "[-] Error parsing data " + str(e)
预期输出:
name = "john-burk"
state = "AL"
引用 str.split
文档,
str.split([sep[, maxsplit]])
If sep is not specified or isNone
, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.
所以,你可以简单地做
name, state = line.split()
print name, state
由于我们没有指定分隔符,所以Python将根据任意数量的连续空白字符作为分隔符进行分割。因此,您的数据可以分为 name
和 state
注意: 如果 name
有任何空白字符,这将不起作用。