簡體   English   中英

如何在python中拆分?

[英]How do i split this in python?

可以說有一個包含以下內容的表:

<td>Dog,Cat,Mouse</td>
<td>Snake,Dragon,Dinosaur,Lizard</td>
<td>Owl,Falcon,Phoenix</td>

我想在python上做到這一點:

>>>pets
[['Dog'],['Cat'],['Mouse'],['Snake'],['Dragon'],['Dinosaur'],['Lizard'],['Owl'],['Falcon'],['Phoenix']]

這是我到目前為止所完成的。

animal = table.find_all('td')
pets = []
for i in animal:
    a = re.findall('[A-Z][a-z]*',str(i))
    pets.append(a)

但是,我找不到辦法

['Dog','Cat','Mouse'] 

['Dog'],['Cat'],['Mouse'], 

等等。 請幫忙。 這是我編程的前幾天,即時通訊已經停滯了。 提前致謝。

import re
strs = """<td>Dog,Cat,Mouse</td>
<td>Snake,Dragon,Dinosaur,Lizard</td>
<td>Owl,Falcon,Phoenix</td>"""

r = re.compile(r'<td>(.*?)</td>')
print [[x] for m in r.finditer(strs) for x in m.group(1).split(',')]

打印:

[['Dog'], ['Cat'], ['Mouse'], ['Snake'], ['Dragon'], ['Dinosaur'], ['Lizard'], ['Owl'], ['Falcon'], ['Phoenix']]

並在同一行上支持多個<td>..</td>

首先,您應該知道regex (正則表達式)並非始終是解析某些數據的最佳解決方案。 例如,在這里,所有元素都由分隔,因此split方法是解決之道。

至於將元素作為具有單個元素的數組放置,列表理解是最簡單的方法。 再次:確保您確實想要/需要這樣做。 擁有一個包含單個元素的列表並沒有多大意義。

這是建議的實現:

elements = table.find_all('td')
pets = []
for e in elements:
    # The following line is only needed if 'find_all' keeps the <td> and </td>
    e_tagless = e[5:len(e)-5]

    animals = e_tagless.split(',')
    pets += [ [animal] for animal in animals ]

嘗試這個:

>>> my_list = ['Dog','Cat','Mouse'] 
>>> map(lambda x: [x], my_list)
[['Dog'], ['Cat'], ['Mouse']]

更改此:

animal = table.find_all('td')
    pets = []
    for i in animal:
       a = re.findall('[A-Z][a-z]*',str(i))
       pets.append(a)

對此:

animal = table.find_all('td')
    pets = []
    for i in animal:
       a = re.findall('[A-Z][a-z]*',str(i))
       pets.append([a])

在循環迭代過程中追加將每個項目標記到其自己的列表中時,您只是缺少了兩個字符[]

暫無
暫無

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

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