在一个Python语句中使用字典一次更改多个关键字

2024-03-29 01:56:33 发布

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

有没有办法像使用字典一样使用字典str.contains公司?你知道吗

我有一本字典,它看起来像这样:

A = {'Hey':1}

我知道对于字典,它会寻找精确的匹配(区分大小写和空格),所以我不知道是否有可能做到这一点。你知道吗

我的数据帧如下所示:

          Statements
0    Hey how are you?
1    Hey is their anyway to find that
2    Hey is their a way to prove this
3    over their, hey, how are you?

我想做的是使用我的字典,基本上检查语句中的每一行,如果字符串包含Hey,请将其更改为1,此外,如果我可以这样做,我想知道是否可以在字典中放入多个语句?像这样:

A={'Hey'、'Hello'、'Hi':1}

我想做的是把一堆可能的字符串放入字典中,如果在语句中找到了这些字符串,那么根据需要进行更改。在本例中,Hey是语句中唯一会被更改的单词。你知道吗

我的预期结果如下:

          Statements
0    1 how are you?
1    1 is their anyway to find that
2    1 is their a way to prove this
3    over their, 1, how are you?

Tags: to字符串you字典thatis语句find
3条回答

我认为您可以先创建dict of list,然后将keysvalues交换为d^{}

L = ['Hey how are you?',
     'Hey is their anyway to find that',
     'Hey is their a way to prove this',
     'over their, hey, how are you?']

df = pd.DataFrame({'Statements':L})

A = {'1':['Hey', 'Hello', 'Hi', 'hey']}
d = {k: oldk for oldk, oldv in A.items() for k in oldv}
print (d)
{'Hi': '1', 'hey': '1', 'Hey': '1', 'Hello': '1'}

df['Statements'] = df['Statements'].replace(d, regex=True)
print (df)
                       Statements
0                  1 how are you?
1  1 is their anyway to find that
2  1 is their a way to prove this
3     over their, 1, how are you?

有一个更好的方法可以做到这一点,但希望在进入会议前发布:)

首先,逻辑如下 1) 遍历列表中的每个元素 2) 把这句话分成两部分 3) 把句子中的每个单词循环一遍,检查是否有数学题 4) 如果匹配,则更新索引

假设a是一本字典

for line in a:
    sentence = line.split()
    for word in sentence:
        if word == 'Hey':
           # Found an index which contains the word so update the index here
           a[line] = 'New value for index'

有点迂回的方式做,但允许你检查任何数量的话,你想在一行。你知道吗

for i in range(df.shape[0]):
    line_split = df['Statements'][i].split()
    for j in range(len(line_split)):
        if line_split[j] in (['Hey', 'hey']):
           line_split[j] = '1'
    df['Statements'][i] = ' '.join(line_split)

相关问题 更多 >