给定一个带有相关信息的单词的有序列表(或元组列表)。我想用其他字符串替换一些字符串,但要跟踪相关的信息。
假设我们有一个简单的例子,我们的输入数据是两个列表:
words = ["hello", "I", "am", "I", "am", "Jone", "101"]
info = ["1", "3", "23", "4", "6", "5", "12"]
输入也可以只是元组列表:
list_tuples = list(zip(words, info)))
“list_words”的每个项具有来自“list_info”的相关联的项(具有相同的索引)。例如,“hello”对应于“1”,第二个“I”对应于“4”。
我想应用一些规范化规则将它们转换为:
words = ["hello", "I'm", "I'm", "Jone", "one hundred and one"]
info = ["1", ["3", "23"], ["4", "6"], "5", "12"]
或者另一种可能的解决方案:
words = ["hello", "I'm", "I'm", "Jone", "one", "hundred", "and", "one"]
info = ["1", ["3", "23"], ["4", "6"], "5", "12", "12", "12", "12"]
请注意,这是一个简单的情况,其思想是应用多个规范化规则(数字到单词,替换,其他缩写等)。我知道如何使用正则表达式将字符串转换为另一个字符串,但在这种情况下,我会丢失相关信息:
def normalize_texts_loosing_info(text):
# Normalization rules
text = re.sub(r"I am", "I\'m", text)
text = re.sub(r"101", "one hundred and one", text)
# other normalization rules. e.g.
# text = re.sub(r"we\'ll", "we will", text)
# text = re.sub(r"you are", "you\'re", text)
# ....
return text.split()
words = ["hello", "I", "am", "I", "am", "Jone", "101"]
print(words)
print(" ".join(words))
output = normalize_texts(" ".join(words))
print(output)
问题是我如何对一个有序的字符串/单词列表应用一些转换,但保留这些单词的相关信息?
PD:谢谢你所有有用的评论
4条答案
按热度按时间dldeef671#
IIUC,如果顺序并不重要,一种简单的方法是迭代字符串中的每个单词,将它们的值(* 如果有的话 *)替换并存储在一个临时字典中,该字典稍后将与原始字典的副本合并:
测试/输出:
0vvn1miw2#
使用
regex
库的partial
匹配功能,可以跟踪哪些模式仍然适用。这个函数使用更合理的
list[tuple]
数据表示,而不是保持两个列表同步。转换被定义为从regex.Pattern
示例(即不是正则表达式本身)到字符串序列的Map。如果你需要更复杂的转换,比如更类似于re.sub
的输入,您可以通过替换transformations
dict中的值并修改本地apply
函数来处理它。kulphzqa3#
答:这不是一个明确的答案……只是个建议
与其尝试使用
join()
来“规范化”创建的字符串,为什么不尝试使用字典键的list
呢?这种方法需要你迭代键,你可以这样定义规则:当然,您可能必须使用
try
和except
来避免IndexError
,以防在字典的末尾遇到“I”。brccelvz4#
有一个方便的num2words模块可以将数字转换为单词。利用这个和一份名单现在是秩序维护。转换回字典。