Python中如何使用index方法获取字符串值

2024-04-18 21:58:02 发布

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

我需要将文本文件的文本分为两类:

University
Location(Example: Lahore, Peshawar, Jamshoro, Faisalabad)

但文本文件包含以下文本: “拉合尔帝国商学院”
“费萨拉巴德政府学院大学”
“拉合尔帝国商学院”
“白沙瓦大学,白沙瓦”
“Jamshoro信德大学”

代码:

for l in content:
    rep = l.replace('"','')
    if ',' in rep:
        uni = rep.split(',')[0]
        loc = rep.split(',')[-1].strip()
    else:
        loc = rep.split(' ')[-1].strip()
        uni = rep.split(' ').index(loc)

它返回以下输出,其中3和5是城市前的指数值:

  • 3代表政府学院大学
  • 5代表帝国商学院

大学:帝国商学院地点:拉合尔
统一:3地点:费萨拉巴德
Uni:5地点:拉合尔
大学:白沙瓦大学地点:白沙瓦
大学:信德大学地址:Jamshoro

我希望程序根据索引值3和5返回字符串值。


Tags: in文本代表loc大学学院帝国uni
2条回答

只需循环通过并将最后一个元素作为位置:

content = [
    "Government College University Faisalabad",
    "Imperial College of Business Studies Lahore",
    "University of Peshawar, Peshawar",
    "University of Sindh, Jamshoro"]

locs = [l.split()[-1] for l in content]
print locs 

['Faisalabad'、'Lahore'、'Peshawar'、'Jamshoro']

在没有逗号的情况下,行

loc = rep.split(' ')[-1].strip()
uni = rep.split(' ').index(loc)

首先找到位置作为字符串的最后一个元素,然后告诉您字符串出现在哪个索引处。你想要的是字符串中的最后一个字以外的所有东西

uni = ' '.join(rep.split()[:-1])

最好先用“”替换,这样就只有一个案例需要处理。而且,我倾向于只把绳子劈开一次。你知道吗

words = rep.split()   # the default is to split at whitespace
loc = words[-1]
uni = ' '.join(words[:-1])

所以,我会这样写循环:

for l in content:
    rep = l.strip('"').replace(',','')
    words = rep.split()  
    loc = words[-1]
    uni = ' '.join(words[:-1])
    print(uni, loc)

这个指纹

('Imperial College of Business Studies', 'Lahore')
('Government College University', 'Faisalabad')
('Imperial College of Business Studies', 'Lahore')
('University of Peshawar', 'Peshawar')
('University of Sindh', 'Jamshoro')

我想这就是你想要的。你知道吗

相关问题 更多 >