我正在嘗試讀取每行包含單詞的 url,我想從 url 中取出每一行并將其附加到我的串列中。使用我擁有的代碼,它只附加來自 url 的第一行,然后停止。我以為我的 for 回圈會解決這個問題,但事實并非如此。我把我的代碼放在下面,其中還包括我所指的網址。
import urllib.request
listOfStrings = []
try:
with urllib.request.urlopen('https://www.cs.queensu.ca/home/cords2/bingo.txt') as f:
for line in f:
d = f.read().decode('utf-8')
split = d.split("\n")
listOfStrings.append(line)
except urllib.error.URLError as e:
print(e.reason)
print(listOfStrings)
uj5u.com熱心網友回復:
我相信您正在尋找的實際上包含在 value 中split。當您在字串上使用 .split 時,它會回傳由您選擇的分隔符分割的字串串列,在本例中為\n。通過洗掉單個行讀取,您可以捕獲所有值:
with urllib.request.urlopen('https://www.cs.queensu.ca/home/cords2/bingo.txt') as f:
d = f.read().decode('utf-8')
split= d.split("\n")
print(split)
回傳:
['motorcycle', 'police car', 'fire truck', 'ambulance', 'military vehicle', ...]
uj5u.com熱心網友回復:
您應該使用readlines而不是整個檔案:
import urllib.request
try:
with urllib.request.urlopen('https://www.cs.queensu.ca/home/cords2/bingo.txt') as f:
list_of_items = f.readlines()
except urllib.error.URLError as e:
print(e.reason)
print(list_of_items)
f是檔案指標,檔案指標型別的方法之一是readlines(). 這為您提供了每一行(由 分隔\n),而您無需手動決議它。在這種情況下,效果很好,您可以簡單地使用它的輸出。
我們可以在 REPL 中看到這一點:
>>> with urllib.request.urlopen('https://www.cs.queensu.ca/home/cords2/bingo.txt') as f:
... list_of_items = f.readlines()
...
>>> list_of_items
[b'motorcycle\n', b'police car\n', b'fire truck\n', b'ambulance\n', b'military vehicle\n', b'bus\n', b'airport shuttle\n', b'limousine\n', b'Hummer\n', b'Mini-Cooper\n', b'PT Cruiser\n', b'Austin Healey\n', b'convertible\n', b'electric car\n', b'bicycle\n', b'cows\n', b'stop sign\n', b'camper\n', b'taxi\n', b'pizza delivery\n', b'tow truck\n', b'dump truck\n', b'cemetary\n', b'logging truck\n', b'mattress on roof\n', b'sailboat\n', b'hotel\n', b'willow tree\n', b'blue van\n', b'flying pig\n', b'sports team bumper sticker\n', b'Canadian flag\n', b'service center\n', b'dog in car\n', b'someone stopped by police\n', b'for sale sign\n', b'revolving sign\n', b'birds on a wire\n', b'field of flowers\n', b'clothesline\n', b'traffic cone\n', b'a shoe on the road\n', b'Tim Hortons\n', b'baseball game\n', b'airplane\n', b'license plate starting with A\n', b'Quebec license plate\n', b'US license plate\n', b'yeild sign\n', b'construction sign\n', b'baby on board sign\n', b'church\n', b'barn\n', b'hawk\n']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/379283.html
