比较字符串和替换单词

时间:2020-08-10 04:44:48

标签: python

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

目前的想法是将list A的文本与 list B的标记进行比较。这里出现不便之处是条件仅说明text [0]中是否有list B,现在可以替换该单词(单词,因为文本[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")

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

2 个答案:

答案 0 :(得分:0)

目前还不清楚您到底想做什么,是否使用正则表达式,如果这些短语可能是值列表的一部分,或者您是否想找到一种遍历选项的好方法,看看是否查找集中存在单词。

对于第一个选项,请检查库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

答案 1 :(得分:0)

根据您的问题,您似乎想检查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语句将listXlistB的每个元素进行比较。如果其中任何一个为真,则它将打印'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')]