我有一个包含多行的字符串。每一行都被' \ n'并在每个单词后面包含逗号。我想将每行中的第一个单词存储到列表中。
这是字符串输出:
AIG,10,,,,Yes,,,Jr,,,MS,,
Baylor College of Medicine,19,Yes,Yes,,,,,,,,,,Recent
CGG,17,Yes,Yes,,,,,,,,MS,PhD,Recent
Citi,27/28,Yes,,,Yes,,,Jr,Sr,,,,
我的列表应为['AIG', 'Baylor College of Medicine', 'CGG', 'Citi']
我想在第一个逗号之后使用split然后转到下一行,但我不知道如何实现这一点。
<小时/> 我的解决方案是返回我的代码并搜索&#34;公司&#34;我之前做过。
公司=
['AIG,10,,,,Yes,,,Jr,,,MS,,\n', 'Baylor\xa0College\xa0of\xa0Medicine,19,Yes,Yes,,,,,,,,,,Recent\n', 'CGG,17,Yes,Yes,,,,,,,,MS,PhD,Recent\n', 'Citi,27/28,Yes,,,Yes,,,Jr,Sr,,,,\n', 'ExxonMobil,11,Yes,,,Yes,Fr,Soph,Jr,Sr,PB,,,\n', 'Flow-Cal\xa0Inc.,16,Yes,,,Yes,,,Jr,Sr,,,,All\n', 'Global\xa0Shop\xa0Solutions,18,Yes,,,Yes,,,,Sr,PB,,,All\n']
cmpny_name = []
for i in companies:
cmpny_name.append(i.split(',', 1)[0])
cmpny_name = [c.replace('\xa0', ' ') for c in cmpny_name]
print(cmpny_name)
OUTPUT:['AIG', 'Baylor College of Medicine', 'CGG', 'Citi', 'ExxonMobil', 'Flow-Cal Inc.', 'Global Shop Solutions', 'Harris County CTS', 'HCSS', 'Hitachi Consulting', 'HP Inc.', 'INT Inc.']
答案 0 :(得分:4)
我会两次使用split
:
lines = string.split('\n')
output = [line.split(',')[0] for line in lines]
答案 1 :(得分:3)
我稍微简化了@Amely的回答
from pprint import pprint
a="this is line 1\nthat is line 2\nthose are line3\nbill was here\nbob was here"
first = [line.split(' ')[0] for line in a.split('\n')]
pprint(first)
你会得到每行的第一句话
['this', 'that', 'those', 'bill', 'bob']
答案 2 :(得分:2)
您可以使用regex
执行某些操作:
>>> import re
>>> b=sum([re.findall(r'^[^,]+(?=,)', i) for i in a], [])
>>> b
['AIG', 'Baylor\xa0College\xa0of\xa0Medicine', 'CGG', 'Citi', 'ExxonMobil', 'Flow-Cal\xa0Inc.', 'Global\xa0Shop\xa0Solutions']
答案 3 :(得分:1)
一行
attributes
yourstring.split返回所有行的列表,并在每行中将其拆分为以逗号分隔的列表,然后选择此列表中的第一个元素。