[英]Python - Replace list of characters with another list
我有两个清单:
wrong_chars = [
['أ','إ','ٱ','ٲ','ٳ','ٵ'],
['ٮ','ݕ','ݖ','ﭒ','ﭓ','ﭔ'],
['ڀ','ݐ','ݔ','ﭖ','ﭗ','ﭘ'],
['ٹ','ٺ','ٻ','ټ','ݓ','ﭞ'],
]
true_chars = [
['ا'],
['ب'],
['پ'],
['ت'],
]
对于给定的字符串,我想将wrong_chars
的条目替换为wrong_chars
中的true_chars
。 在python中有没有一种干净的方法来做到这一点?
string
模块来救援!
有一个非常方便的函数作为string
模块的一部分,称为translate
,它完全符合您的要求,尽管您必须将翻译映射作为字典传递。
文档在 这里
下面显示了一个基于tutorialapoint教程的示例:
>>> from string import maketrans
>>> trantab = maketrans("aeiou", "12345")
>>> "this is string example....wow!!!".translate(trantab)
th3s 3s str3ng 2x1mpl2....w4w!!!
看起来您在这里使用的是 unicode,但工作方式略有不同。 你可以看看这个问题来了解一下,但这里有一个更适合你的例子:
translation_dict = {}
for i, char_list in enumerate(wrong_chars):
for char in char_list:
translation_dict[ord(char)] = true_chars[i]
example.translate(translation_dict)
我将您的两个错误和真实字符合并到了错误字典列表中,以及应该用它们替换的内容。 所以你在这里:
链接到工作示例http://ideone.com/mz7E0R
和代码本身
given_string = "ayznobcyn"
correction_list = [
{"wrongs":['x','y','z'],"true":'x'},
{"wrongs":['m','n','o'],"true":'m'},
{"wrongs":['q','r','s','t'],"true":'q'}
]
processed_string = ""
true_char = ""
for s in given_string:
for correction in correction_list:
true_char=s
if s in correction['wrongs']:
true_char=correction['true']
break
processed_string+=true_char
print given_string
print processed_string
这段代码可以更优化,当然我不关心 unicode 问题(如果有的话),因为我看到你在使用波斯语。 你应该注意这一点。
#!/usr/bin/env python
from __future__ import unicode_literals
wrong_chars = [
['1', '2', '3'],
['4', '5', '6'],
['7'],
]
true_chars = 'abc'
table = {}
for keys, value in zip(wrong_chars, true_chars):
table.update(dict.fromkeys(map(ord, keys), value))
print("123456789".translate(table))
aaabbbc89
在我的想法中,您可以只制作一个包含真实字符的列表,如下所示:
NewChars = {["ا"،"أ"،"إ"،"آ"], ["ب"،"بِ"،"بِ"،]}
# add all true characters to the first of lists and add all lists to a dict, then:
Ch="إ"
For L in NewChars:
If Ch in L: return L[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.