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

使用字典在一条Python语句中一次更改多个关键字,python,dictionary,dataframe,Python,Dictionary,Dataframe,有没有办法像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, he

有没有办法像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':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?

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

首先,逻辑将如下所示 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'

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

首先,逻辑将如下所示 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)

这是一种简单的方法,但允许您在一行中检查任意数量的单词

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)

我认为您可以先创建目录列表,然后将
交换到
d
,然后:


我认为您可以先创建目录列表,然后将
交换到
d
,然后:


预期结果是什么?我将编辑以显示预期结果,我想要的是在它看到的任何地方将其更改为1,但使用字典我知道它会查看整个字符串我想知道您是否可以按字符串中可能包含特定单词或字符串的部分查看它。预期结果是什么?我将进行编辑以显示预期结果,我想要的是无论它在哪里看到Hey都将其更改为1,但使用字典,我知道它会查看整个字符串,我想知道您是否可以按字符串中可能包含特定单词或字符串的部分查看它。Smart。这就是答案。@AlexF-谢谢你,聪明。这就是答案。@AlexF-谢谢你。