我在解決以下問題時遇到了一些問題。
我必須 *.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(),因為您可以比較兩個檔案中的串列元素。但我不允許這樣做。
我希望有人可以幫助我,并對長文本感到抱歉。
uj5u.com熱心網友回復:
這是基于我之前評論的實作:
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
uj5u.com熱心網友回復:
這只是一個提示,畢竟這是你的大學作業。
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/410149.html
標籤:
