简体   繁体   English

如何在以“;”分隔的文件行中拆分单词

[英]How to split words in line of a file separated by “;”

How to split the words in line separated by ;如何拆分由;分隔的行中的单词:

10103;Baldwin, C;SFEN
10115;Wyatt, X;SFEN
10172;Forbes, I;SFEN
10175;Erickson, D;SFEN
10183;Chapman, O;SFEN
11399;Cordova, I;SYEN
11461;Wright, U;SYEN
11658;Kelly, P;SYEN
11714;Morton, A;SYEN
11788;Fuller, E;SYEN

Is this what you're looking for?这是你要找的吗?

line = "10103;Baldwin, C;SFEN 10115;Wyatt, X;SFEN 10172;Forbes, I;SFEN 10175;Erickson, D;SFEN 10183;Chapman, O;SFEN 11399;Cordova, I;SYEN 11461;Wright, U;SYEN 11658;Kelly, P;SYEN 11714;Morton, A;SYEN 11788;Fuller, E;SYEN"
line.split(";")

Output Output

['10103',
 'Baldwin, C',
 'SFEN 10115',
 'Wyatt, X',
 'SFEN 10172',
 'Forbes, I',
 'SFEN 10175',
 'Erickson, D',
 'SFEN 10183',
 'Chapman, O',
 'SFEN 11399',
 'Cordova, I',
 'SYEN 11461',
 'Wright, U',
 'SYEN 11658',
 'Kelly, P',
 'SYEN 11714',
 'Morton, A',
 'SYEN 11788',
 'Fuller, E',
 'SYEN']

one alternative:一种选择:

"10103;Baldwin, C;SFEN".split(";")

However, I think you want to separate everything (including the commas)so I would do a replace of the ";"但是,我认为您想将所有内容(包括逗号)分开,所以我会替换“;” first into commas and then doing the split by commas.首先用逗号分隔,然后用逗号分隔。

I suggest using csv for this, although if your input is actually a string then you'll need io.StringIO or just split by newline:我建议为此使用csv ,尽管如果您的输入实际上是一个字符串,那么您将需要io.StringIO或仅由换行符拆分:

import csv
from io import StringIO

s = """10103;Baldwin, C;SFEN
10115;Wyatt, X;SFEN
10172;Forbes, I;SFEN
10175;Erickson, D;SFEN
10183;Chapman, O;SFEN
11399;Cordova, I;SYEN
11461;Wright, U;SYEN
11658;Kelly, P;SYEN
11714;Morton, A;SYEN
11788;Fuller, E;SYEN"""

reader = csv.reader(s.split('\n'), delimiter=';')
#or
reader = csv.reader(StringIO(s), delimiter=';')
for line in reader:
    print(line)

Output: Output:

['10103', 'Baldwin, C', 'SFEN']
['10115', 'Wyatt, X', 'SFEN']
['10172', 'Forbes, I', 'SFEN']
['10175', 'Erickson, D', 'SFEN']
['10183', 'Chapman, O', 'SFEN']
['11399', 'Cordova, I', 'SYEN']
['11461', 'Wright, U', 'SYEN']
['11658', 'Kelly, P', 'SYEN']
['11714', 'Morton, A', 'SYEN']
['11788', 'Fuller, E', 'SYEN']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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