在列表中添加.csv文件后,如何从列表中选择关键字?

2024-06-16 13:59:23 发布

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

我需要能够从Excel CSV文件中选择关键字,我已将该文件附加到列表中。这个程序是一个电话故障排除,我需要输入(“屏幕不会打开”)有相同的输出,如果我输入(“显示空白”)。你知道吗

"Troubleshooting Program to give the user a solution to a trouble they've     encountered based on inputted key words."

phoneprob=input("What problem are you having with your phone? ")
prob=open("phone.csv","r")
phone=prob.read()
prob.close()
eachProb=phone.split("\n")

print(eachProb)
problist=[eachProb]

print (problist)

Tags: 文件csvto程序列表屏幕phone关键字
1条回答
网友
1楼 · 发布于 2024-06-16 13:59:23

你是想建立一个关键词词典还是重审一个句子问题? 在这两种情况下,都需要将问题与关键字关联起来。你知道吗

获取关键字的基本方法是将句子拆分为单词(使用s.split()),并用最常用的单词更新关键字列表。。。 difflib在这里可以帮忙。你知道吗

因为我们不知道给定的文件模式,所以我假设它只是一个句子列表,而您在其他地方提供了关键字/问题(situation Dict)。你知道吗

例如:

csv_ret = ["I can't turn on my phone", "The screen won't turn on", "phone The display is blank"]

situations = {
    "screen": ["turn on", "blank", "display", "screen"],
    "battery": ["turn on", "phone"]
}


def get_situation_from_sentence(sentence):
    occurences = {}
    for word in sentence.split():
        for key, value in situations.items():
            if word in value:
                if occurences.get(key) is None:
                    occurences[key] = [word]
                elif word not in occurences.get(key):
                    occurences[key].append(word)
    averages = {k: ((len(v) * 100) / len(situations[k])) for k, v in occurences.items()}
    return "{}, {}".format(averages, sentence)

for sentence in csv_ret:
    print(get_situation_from_sentence(sentence))

结果:

{'battery': 50.0}, I can't turn on my phone

{'screen': 25.0}, The screen won't turn on

{'screen': 50.0, 'battery': 50.0}, phone The display is blank

此代码以百分比计算句子问题和相关关键字匹配。你知道吗

同样,这是一个非常基本的解决方案,您可能需要一些更健壮的解决方案(lexer/parser、机器学习……),但有时更简单更好:)

相关问题 更多 >