简体   繁体   English

用于在python中查找替换列表的itertools或functools

[英]itertools or functools for find-replace list in python

I have a set of strings that are sometimes invalid that I'd like to replace with particular better strings. 我有一组有时无效的字符串,我想用特别好的字符串替换。 I've been playing with functools and itertools and would like to try applying these to the problem, but I'm a little stuck. 我一直在玩functools和itertools,并想尝试应用这些问题,但我有点卡住了。 Here's what I have: 这就是我所拥有的:

s1 = 'how to sing songs'
s2 = 'This is junk'
s3 = "This is gold"
s4 = 'HTML'
s5 = 'html'
s6 = 'i'
mylist = [s1,s2,s3,s4,s5,s6]

replacements = [('html','HTML'),('how to sing songs','singing'),('This is junk', ''),('i','')]

I'd like a function algorithm that sort of says, for each string in mylist, for each replacement in replacements, string.replace(replacement[0],replacement[1]). 我想要一个函数算法,对于mylist中的每个字符串,对于替换中的每个替换,string.replace(replacement [0],replacement [1])。

What kind of came to mind was something like... 想到什么样的东西就像......

map(lambda x,y: x.replace(y[0],y[1]),mylist,replacements)
map(partial(lambda x,y: x.replace(y[0],y[1]),mylist),replacements)

But the first wanted extra arguments, and the second said list object has no attribute replace. 但是第一个想要额外的参数,第二个说列表对象没有属性替换。 Is there a slick functional way to solve this? 有没有一个灵活的功能方式来解决这个问题?

>>> [reduce(lambda x, y: x.replace(y[0], y[1]), replacements, s) for s in mylist]
['singing', '', 'This is gold', 'HTML', 'HTML']

Equivalent code with map() instead of a list comprehension: 使用map()而不是list comprehension的等效代码:

map(partial(reduce, lambda x, y: x.replace(y[0], y[1]), replacements), mylist)

Sounds like you want something really fast. 听起来你想要一些非常快的东西。 In that case you should really be using dictionaries, as lookups are extremely fast. 在这种情况下,你应该真正使用字典,因为查找非常快。

A working example: 一个工作的例子:

mylist = ['how to sing songs', 'This is junk', "This is gold", 'HTML', 'html', 'i']
replacements = {'html':'HTML', 'how to sing songs':'singing', 'This is junk':'', 'i':''}

print [replacements.get(word, word) for word in mylist]  
# ['singing', '', 'This is gold', 'HTML', 'HTML', ''] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM