比较字符串和替换单词

2024-10-06 10:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

列表A表示将替换为列表B的链接和标签的文本

这个想法是比较list A的文本和 list B的标记,现在可以了。这里出现的不便之处在于,条件只说明list B中是否有text [0],现在作为该单词的替代词(单词,因为文本[0]“客户的时钟工作正常。”使用“watch,customer”一词),因此每个单词代表不同的链接

listA = ['Text with label A', 'Label B with text', 'Text without label', 'Only text']
listB = [('urlA', 'label A'), ('urlB', 'label B'), ('urlC', 'label C')]

for uri, label in listB:
    print(uri, label)
    
if any('label A' in label for uri, label in listB):
    print("contains something")
else:
    print("nothing")

条件是一样的(理论上不是吗?),我不知道为什么不找点东西

for datail in listA:
    print(datail)
    if any(datail in label for url, label in listB):
        # condition is bad
        print("contains something")
        # how to replace that word with the tag and its url
        detalle = detalle.replace('', '')
    else:
        print("nothing")

总而言之,我正在尝试执行语义注释,突然出现了一些库或更有效的东西


Tags: textin文本列表for链接withuri
2条回答

根据您的问题,您似乎想检查listA中的任何项目是否是listB的一部分

让我们首先将listA转换成一个元组,看起来像listB

listA = ['abc - 123', 'def - 456', 'ghi - 789', 'abc - 456']

#this will convert listA into a tuple like listB
listX = [tuple(i.split(' - ')) for i in listA]

既然listAlistB看起来都一样,您可以将它们相互比较

下面的if语句将listX的每个元素与listB进行比较。如果其中任何一个为真,那么它将打印'contains something'

if any(True for i, j in zip(listX, listB) if i == j):
    print("contains something")
else:
    print("nothing")

但是,如果您想知道listAlistB之间匹配的所有项目,那么可以使用下面两行

temp = [x for x in listX for b in listB if x == b]       
print (temp)

完整代码如下所示:

listA = ['abc - 123', 'def - 456', 'ghi - 789', 'abc - 456']
listB = [('abc', '123'), ('def', '456'), ('ghi', '789')]

#convert listA into a tuple to compare with listB
listX = [tuple(i.split(' - ')) for i in listA]

#check if any item in listX matches with listB
if any(True for i, j in zip(listX, listB) if i == j):
    print("contains something")
else:
    print("nothing")

#for each item that matches from listA with listB, store into temp
temp = [x for x in listX for b in listB if x == b]

#temp contains all matched items betwen listA and listB
print (temp)

输出:

contains something
[('abc', '123'), ('def', '456'), ('ghi', '789')]

现在还不清楚您到底想做什么,如果短语可能是值列表的一部分,是否正在使用正则表达式,或者是否正在尝试找到一种好的方法来迭代您的选项,并查看单词是否存在于查找集中

对于第一个选项,请查看库re,它有助于执行正则表达式和类似的操作

re.search(my_pattern, string_to_check)

对于第二种情况,我建议使用字典,因为您可以很容易地查看字典的键中是否存在值,然后获得相应的输出

my_lookup_table = {"a": 1, "b": 2, "c": 3}
test_values = ["a", "a", "d", "c"]

for value in test_values:
    if value in my_lookup_table.keys():
        print(my_lookup_table[value])
# prints 1, 1, 3

相关问题 更多 >