2017-08-15 45 views
1

假設我有很多沒有換行符的HTML。我想把每個元素都放到一個列表中。Python:兩個字符之間的分割

input = "<head><title>Example Title</title></head>" 

a_list = ["<head>", "<title>Example Title</title>", "</head>"] 

就像這樣。分裂在每個><之間。

但在Python中,我不知道一種方法來做到這一點。我只能將分割爲這個字符串,它將它從輸出中移除。我想保留它,並在兩個平等運算符之間進行分割。

這怎麼辦?

編輯:優選地,這將在沒有將字符添加回每個列表項目的末尾的情況下完成。

+0

請從'a_list'發佈您想要的輸出。 – Ajax1234

+1

@Carcigenicate BS4不是一種選擇。這不是我實際做的一個例子。這不是問題,問題在於標題。我需要分割兩個字符,我不關心示例HTML。它始終顯示相鄰的「>」字符之間的分隔,這就是我所要做的。 – spikespaz

+0

@ Ajax1234示例列表是我需要的輸出。 – spikespaz

回答

3

你可以試試這個:

import re 
a = "<head><title>Example Title</title></head>" 

data = re.split("><", a) 

new_data = [data[0]+">"]+["<" + i+">" for i in data[1:-1]] + ["<"+data[-1]] 

輸出:

['<head>', '<title>Example Title</title>', '</head>'] 
3
# initial input 
a = "<head><title>Example Title</title></head>" 

# split list 
b = a.split('><') 

# remove extra character from first and last elements 
# because the split only removes >< pairs. 
b[0] = b[0][1:] 
b[-1] = b[-1][:-1] 

# initialize new list 
a_list = [] 

# fill new list with formatted elements 
for i in range(len(b)): 
    a_list.append('<{}>'.format(b[i])) 

這將輸出在Python 2.7.2給定的名單,但它應該在Python 3正常工作。

+0

這不會輸出任何東西。 – wpercy

0

或者更簡單的做法是:

input = "<head><title>Example Title</title></head>" 
print(['<'+elem if elem[0]!='<' else elem for elem in [elem+'>' if elem[-1]!='>' else elem for elem in input.split('><') ]]) 
2

使用上擴展的例子re.findall()功能的最短途徑:

# extended html string 
s = "<head><title>Example Title</title></head><body>hello, <b>Python</b></body>" 
result = re.findall(r'(<[^>]+>[^<>]+</[^>]+>|<[^>]+>)', s) 
print(result) 

輸出:

['<head>', '<title>Example Title</title>', '</head>', '<body>', '<b>Python</b>', '</body>'] 
1

基於通過答案其他人,我做了這個。

它不像我想要的那樣乾淨,但它似乎工作。我原本想在分割後不重新添加字符。

在這裏,我擺脫了一個額外的參數,將兩個字符組合成一個字符串。不管怎麼說,

def split_between(string, chars): 
    if len(chars) is not 2: raise IndexError("Argument chars must contain two characters.") 

    result_list = [chars[1] + line + chars[0] for line in string.split(chars)] 

    result_list[0] = result_list[0][1:] 
    result_list[-1] = result_list[-1][:-1] 

    return result_list 

幸得@cforeman@Ajax1234