繁体   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