[英]Sort with re.search() - Python
我在解決以下問題時遇到了一些問題。
我必須 *.txt 文件中的兩個文件都是來自奧地利的城市。 在第一個文件“cities1”中,城市按人口排序。
第一個文件 (cities1.txt) 如下所示:
1.,Vienna,Vienna,1.840.573
2.,Graz,Styria,273.838
3.,Linz,Upper Austria,198.181
4.,Salzburg,Salzburg,148.420
5.,Innsbruck,Tyrol,126.851
第二個文件 (cities2.txt) 如下所示:
"Villach","Carinthia",60480,134.98,501
"Innsbruck","Tyrol",126851,104.91,574
"Graz","Styria",273838,127.57,353
"Dornbirn","Vorarlberg",47420,120.93,437
"Vienna","Vienna",1840573,414.78,151
"Linz","Upper Austria",198181,95.99,266
"Klagenfurt am Woerthersee","Carinthia",97827,120.12,446
"Salzburg","Salzburg",148420,65.65,424
"Wels","Upper Austria",59853,45.92,317
"Sankt Poelten","Lower Austria",52716,108.44,267
我喜歡做的,或者換句話說我應該做的是,第一個文件cities1.txt
已經排序。 我只需要每行的第二個元素。 這意味着我只需要城市的名稱。 例如從第2.,Graz,Styria,273.838
,我只需要 Graz。
第二個我應該打印出城市的區域,這是cities2.txt
中每一行的第四個元素。 這意味着,例如從第三行"Graz","Styria",273838,127.57,353
,我只需要127.57
。
最后,控制台應顯示以下內容:
Vienna,414.78
Graz,127.57
Linz,95.99
Salzburg,65.65
Innsbruck,104.91
所以,我現在的問題是,如果我只允許使用re.search()
方法,我該怎么做。 因為第二個 *.txt 文件的順序不同,我必須按照與第一個文件中相同的順序來排列城市,這樣才能正常工作,或者?
我知道,使用re.split()
會容易得多,因為您無法比較兩個文件中的列表元素。 但我不允許這樣做。
我希望有人可以幫助我,並對長文本感到抱歉。
這是基於我之前評論的實現:
with open('cities2.txt') as c:
D = {}
for line in c:
t = line.split(',')
cn = t[0].strip('"')
D[cn] = t[-2]
with open('cities1.txt') as d:
for line in d:
t = line.split(',')
print(f'{t[1]},{D[t[1]]}')
請注意,這可能並不可靠。 如果 city1.txt 中的城市名稱在 cities2.txt 中不存在,那么您將收到 KeyError
這只是一個提示,畢竟這是你的大學作業。
import re
TEST = '2.,Graz,Styria,273.838'
RE = re.compile('^[^,]*,([^,]*),')
if match := RE.search(TEST):
print(match.group(1)) # 'Graz'
讓我們分解正則表達式:
^ - start of line
[^,]* - any character except a comma - repeated 0 or more times
this is the first field
, - one comma character
this is the field separator
( - start capturing, we are interested in this field
[^,]* - any character except a comma - repeated 0 or more times
this is the second field
) - stop capturing
, - one comma character
(don't care about the rest of line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.