在句子中查找字典值并输出句子,键

2024-04-29 10:59:51 发布

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

我试图找出一个单词作为字典中的值是否存在于一个句子(csv行)中。如果这个词是在句子中找到的,我希望输出是ID,句子和键。你知道吗

作为数据帧运行python3.6。我可以得到这些值,但不能让循环为.items()工作,以获得要返回的键


dict = {'housing': 'homeless',
           'housing2': 'homelessness',
           'housing3': 'evicted',
           'housing4': 'shelter'}

# dataframe with one row for each ID and sentence 
sentences = []
for row in text.itertuples():
    for sentence in row[2].split('.'):
        if sentence != '': 
            sentences.append((row[1], sentence))
sentence = pd.DataFrame(sentences, columns=['ID', 'sentence'])

#find dictionary value in sentences
def find_sdh(x):
    val = [x for k in dict.values() if k in x]
    if val:
        return val

# link sentence, id, value 
sentence['sdh'] = sentence['sentence'].apply(find_sdh)

# drop null values
df = sentence.dropna(subset=['sdh'])

这提供了与ID和句子匹配的字典值。你知道吗

(ID,sentence)
(246,'This is an example.')
(132,'This is a test.')  
(662,'This is fake data.')  

我需要ID、句子和键(与匹配的值关联)

(ID, sentence, key)
(246, This is an example., key1)
(132, This is a test., key5)
(662, This is fake data, key3)

请,谢谢!你知道吗


Tags: inidforif字典issentencesval
1条回答
网友
1楼 · 发布于 2024-04-29 10:59:51

您只需添加另一个方法以分配给第二列:

def find_keys(x):
    result = [k for k, v in dict.items() if v in x]
    if result:  # not sure you need this
        return result

sentence['keys'] = sentence['sentence'].apply(find_keys)

或者,可以使用不同的方法将(sentence, key)元组分配给新列,但这可能更难处理。我不看好这里的语法,因为我不看好你的数据结构:

def find_stuff(x):
    result = [(x, k) for k, v in dict.items() if v in x]
    if result:  # again not sure you need this
        return result

sentence['stuff'] = sentence.sentence.apply(find_stuff)

关于if result:检查,Python中的每个函数的末尾都有一个隐式的return None。如果列表理解没有给result赋值,那么result只是一个空数组[],它不是None,但两者的计算结果都是False,而且下游代码通常不关心差异。我对.apply()的行为并不肯定,但如果你完全放弃检查并总是返回结果,你可能会有同样的结果。值得检查,因为它使代码更干净。你知道吗

相关问题 更多 >