簡體   English   中英

在Python中替換列表中的部分字符串

[英]Replacing parts of strings in a list in Python

我知道這個主題也存在類似的問題,但是我已經遍歷了這些問題,但仍然無法解決。

我的python程序使用正則表達式從頁面檢索html的一部分。 我只是意識到我並沒有考慮到html特殊字符會妨礙您。

說我有:

regex_title = ['I went to the store', 'Itlt'sa nice day today', 'I went home for a rest']

我顯然想更改lt' 單引號'。

我嘗試了以下的變體:

for each in regex_title:
    if 'lt'' in regex_title:
        str.replace("lt'", "'")

但沒有成功。 我想念什么。

注意:目的是在不導入更多模塊的情況下執行此操作。

str.replace不能就地替換。 它返回替換后的字符串。 您需要分配回值。

>>> regex_title = ['I went to the store', 'Itlt's a nice day today',
...                'I went home for a rest']
>>> regex_title = [s.replace("lt'", "'") for s in regex_title]
>>> regex_title
['I went to the store', "It's a nice day today", 'I went home for a rest']

如果您的任務是對HTML進行轉義,那么最好使用unescape函數:

>>> ll = ['I went to the store', 'Itlt's a nice day today', 'I went home for a rest']
>>> import HTMLParser
>>> h = HTMLParser.HTMLParser()
>>> print map(h.unescape, ll)
['I went to the store', u"Itlt's a nice day today", 'I went home for a rest']

您需要將代碼更改為此:

for each in regex_title:
    if 'lt'' in each:
        each.replace("lt'", "'")

但這不會更改您的列表,因此您需要將替換的索引傳遞給list:

>>> for each in regex_title:
...         if 'lt'' in each:
...             regex_title[regex_title.index(each)]=each.replace("lt'", "'")
... 
>>> regex_title
['I went to the store', "It's a nice day today", 'I went home for a rest']
>>> 

您無需解釋為什么要避免導入標准庫模塊。 很少有理由拒絕使用Python隨附的電池。 除非您有這樣的理由(如果確實如此,則應說明理由),則應使用提供給您的功能。

在這種情況下,它是html模塊中的unescape()函數: 1

from html import unescape

titles = [
    'I went to the store',
    'It's a nice day today',
    'I went home for a rest'
]

fixed = [unescape(s) for s in titles]
>>> fixed
['I went to the store', "It's a nice day today", 'I went home for a rest']

自己重新實現html.unescape()

  1. 無意義。
  2. 容易出錯。
  3. 這意味着要不斷返回並在數據中出現新的HTML實體時添加新案例。

1從Python 3.4開始,無論如何。 對於以前的版本,請按照@stalk的answer使用HTMLParser.HTMLParser.unescape()

最好不要使用HTMLParser庫,而最好自己動手,如https://stackoverflow.com/a/2087433/2314532中所述 閱讀該問題和答案以獲取所有詳細信息,但摘要是:

import HTMLParser
parser = HTMLParser.HTMLParser()
print parser.unescape(''')
# Will print a single ' character

因此,在您的情況下,您想要執行以下操作:

import HTMLParser
parser = HTMLParser.HTMLParser()
new_titles = [parser.unescape(s) for s in regex_title]

這將取消所有 HTML轉義,而不僅僅是' 轉義您要的內容,然后一次處理整個列表。

嘗試這樣:-

 regex_title = ['I went to the store', 'Itlt's a nice day today', 'I went home for a rest']
 str=','.join(regex_title)
 str1=str.replace("lt'","'");    
 print str1.split()

暫無
暫無

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

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