解析唯一字符串?

2024-09-30 22:21:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python非常陌生,但我需要一些帮助来解析具有独特结构的字符串。我有一个CSV文件,其中的列具有以下结构:

[Chakroff, Alek; Young, Liane] Boston Coll, Chestnut Hill, MA 02167 USA; [Russell, Pascale Sophie] Univ Surrey, Guildford, Surrey, England; [Piazza, Jared] Univ Lancaster, Lancaster, England

我只想把分号前的国家名称拉出来。因此,对于以上内容,我想要“美国、英国、英国”。字符串的整体结构为:

[last name, first name], university, address, zip code, country; 

我怎样才能得到这个字符串布局的国家?有没有办法指定分号前的国家名称?或者是一种更简单的方式来获取我需要的信息

请对我宽容点,我无论如何都不是最好的程序员:)


Tags: 文件csv字符串name名称国家结构univ
3条回答

使用正则表达式:

import regex as re

data = "[Chakroff, Alek; Young, Liane] Boston Coll, Chestnut Hill, MA 02167 USA; [Russell, Pascale Sophie] Univ Surrey, Guildford, Surrey, England; [Piazza, Jared] Univ Lancaster, Lancaster, England"
outer_pattern = re.compile(r'\[[^][]+\](*SKIP)(*FAIL)|;')
inner_pattern = re.compile(r'(\w+)\s*$')

countries = [country.group(1)
             for chunk in outer_pattern.split(data)
             for country in [inner_pattern.search(chunk)]
             if country]

print(countries)
# ['USA', 'England', 'England']

可以对字符串使用split()方法

states = [person_record.split(",")[-1] for person_record in records.split("; [")]

其中records是从输入中获得的字符串

可以利用所需元素之前的唯一子字符串:

# split string on substring '; ['
for i in s.split('; ['):
    # split each resulting string on space char, return last element of array
    print(i.split()[-1])

USA
England
England

相关问题 更多 >