gpt4 book ai didi

python - 查找句子中的字典值并输出句子、键

转载 作者:太空宇宙 更新时间:2023-11-03 20:38:46 24 4
gpt4 key购买 nike

我试图查找作为字典中的值的单词是否在句子(csv 行)中找到。如果在句子中找到该单词,我希望输出为 ID、句子和键。

将 python 3.6 作为 pandas 数据帧运行。我可以获取值,但无法让循环为 .items() 工作以获取要返回的 key


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)

请并谢谢您!

最佳答案

您可以添加另一种方法来分配给第二列:

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() 的行为并不乐观,但如果您完全放弃检查并始终返回结果,您可能会得到相同的结果。值得检查,因为它使代码更简洁。

关于python - 查找句子中的字典值并输出句子、键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56992639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com