簡體   English   中英

如何操作列表中的字符串項?

[英]How can I manipulate the string items in a list?

我正在嘗試熟悉使用 python 進行網絡抓取,但無法弄清楚如何操作作為列表一部分的字符串。

下面是我正在嘗試提取在當地劇院放映的電影的代碼,我可以從 HTML 代碼中獲取大部分名稱。 我想要做的是遍歷列表並從列表中的字符串中取出前兩個字符,因為使用正則表達式我不能只在我的嘗試中提取名稱。

它拋出錯誤,因為它將它視為我試圖操作的列表對象,但它是我想要更改的列表中的字符串。

from urllib.request import urlopen
import re
url = "http://woodburytheatre.com/showtimes"
page = urlopen(url)
page
html_bytes = page.read()
html = html_bytes.decode("utf-8")
#print(html)
span_index = html.find("<div id=\"showtimes_wrapper\">")
start_index = span_index + len("<div id=\"showtimes_wrapper\">")
end_index = html.find("<div id=\"t_comingsoon\">")
#print(span_index)
movie_info = html[start_index:end_index]
movie_list = list()
movie_list2 = list()
movie_list3 = list()
#print(movie_info)
for item in movie_info.split("\n"):
   if "showtimes_movie" in item:
       movie_list.append(item.strip())
#print(movie_list)
for item in movie_list:
   movie_list2.append(re.findall("[0-9]\/[A-z0-9\-]+",str(movie_list)))
#print(movie_list2)
while movie_list2:
   temp = movie_list2.pop()
   print(type(temp))
   print("temp" + str(temp))
   temp2 = temp.lstrip("/")
   print(temp2)
   movie_list3.append(temp2)
print(movie_list3)
print(len(movie_list2))
print(movie_list3)

我知道它非常混亂,而且效率更高,但我只想能夠更改列表中的字符串,這樣我就可以擺脫它們之前的數字和“/”。

提前致謝!

在第二個for循環:

for item in movie_list:
   movie_list2.append(re.findall("[0-9]\/[A-z0-9\-]+",str(movie_list)))

來自關於re.findall python 文檔:

def findall(pattern: Pattern[AnyStr],
            string: AnyStr,
            flags: Union[int, RegexFlag] = ...) -> list

re.findall返回所有匹配對象的列表 因此,您將list附加到list ,並且 list 沒有方法lstrip ,導致while循環出錯。

while movie_list2:
   temp = movie_list2.pop()
   print(type(temp))
   print("temp" + str(temp))
   temp2 = temp.lstrip("/")  # << here
   print(temp2)
   movie_list3.append(temp2)

最終,您嘗試存檔的內容可以通過一行來完成:

from urllib.request import urlopen

page = urlopen("http://woodburytheatre.com/showtimes")
html_bytes = page.read()
html = html_bytes.decode("utf-8")

span_index = html.find("<div id=\"showtimes_wrapper\">")
start_index = span_index + len("<div id=\"showtimes_wrapper\">")
end_index = html.find("<div id=\"t_comingsoon\">")

movie_info = html[start_index:end_index]

# this line below
movie_list = [i.split('/')[-1].rstrip(r"'>") for i in movie_info.split("\n") if 'showtimes_movie' in i]
print(movie_list)

輸出:

['Bill-and-Ted-Face-The-Music', 'The-New-Mutants', 'The-Personal-History-of-David-Copperfield', 'Inception-10th-Anniversary', 'Unhinged', 'Made-in-Italy', 'The-Rental', 'Trolls-World-Tour', 'Indiana-Jones-and-the-Temple-of-Doom', 'Indiana-Jones-and-the-Raiders-of-the-Lost-Ark']

有了這個,您可以使用.replace函數簡單地替換連字符。


要詳細了解一行生成器表達式- 又名genexp - 是如何工作的,讓我們看看這個例子:

>>> output = [i for i in range(4) if i != 3]

您可以在genexp 中放置if條件檢查以在創建列表時過濾項目。 這與以下for循環完全相同for但工作速度更快:

>>> output = []
>>> for i in range(4):
...     if i != 3:
...         output.append(i)

您可以再次使用表達式來添加到列表中的項目。
您甚至可以添加完全不相關的東西,而不是保存for循環的i

>>> [[i for i in 'Nope.'] for i in range(2)]
[['N', 'o', 'p', 'e', '.'], ['N', 'o', 'p', 'e', '.']]
>>> ['Nope.' for i in range(4)]
['Nope.', 'Nope.', 'Nope.', 'Nope.']

結合起來,這意味着:

movie_list = [i.split('/')[-1].rstrip(r"'>") for i in movie_info.split("\n") if 'showtimes_movie' in i]
movie_list = []
for i in movie_info.split("\n"):
    if 'showtimes_movie' in i:
        split_strings_list = i.split('/')
        last_item_in_list = split_strings_list[-1]  # python can do backward-indexing
        strip_text_from_right = last_item_in_list.rstrip("'>")  # remove '> from behind of string
        
        movie_list.append(strip_text_from_right)

通過使用enumerate您可以同時獲取列表的索引和項目:

for index, item in enumerate(lst):
    # Strip the first two letters
    list[index] = lst[index][2:]

但是請注意,在 HTML 上使用正則表達式是一個壞主意。 我強烈建議使用 HTML 解析庫,其中最著名的是beautifulsoup4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM