Python 如何从句子中提取主题?
我想把在一份问题报告中提出的问题的所有主题制成表格。这是论文中提出的两个问题的格式示例:Python 如何从句子中提取主题?,python,regex,parsing,nltk,Python,Regex,Parsing,Nltk,我想把在一份问题报告中提出的问题的所有主题制成表格。这是论文中提出的两个问题的格式示例: question1 = 'Write short notes on the anatomy of the Circle of Willis including normal variants.' question2 = 'Write short notes on the anatomy of the axis (C2 vertebra).' 从以上问题中,我希望得到以下主题: topic1 = 'Circ
question1 = 'Write short notes on the anatomy of the Circle of Willis including normal variants.'
question2 = 'Write short notes on the anatomy of the axis (C2 vertebra).'
从以上问题中,我希望得到以下主题:
topic1 = 'Circle of Willis including normal variants'
topic2 = 'axis (C2 vertebra)'
对于以上内容,我编写了以下代码片段:
def extract_topic(message):
message = re.search('Write short notes on the anatomy of the (.+?).', message)
if message:
return message.group(1)
当然,上面的代码失败得很惨!我该怎么办?做上述事情最简单的方法是什么?使用NLTK会使上述操作变得简单吗?试试这个
def extract_topic(message):
message = re.search('Write short notes on the anatomy of the (.*).', message)
if message:
return message.group(1)
- 您的正则表达式只有一个错误,您忘记在结尾转义
,因为
意味着匹配除换行符以外的任何字符。另外,
是非贪婪的,因此它匹配一个字符,然后再匹配一个字符(.+?)
def extract_topic(message):
message = re.search('Write short notes on the anatomy of the (.+?)\.', message)
if message:
return message.group(1)
如果您的数据格式仍然与您显示的相同->非常简单的解决方案是:
question1 = 'Write short notes on the anatomy of the Circle of Willis including normal variants.'
question2 = 'Write short notes on the anatomy of the axis (C2 vertebra).'
list_of_questions = [question1, question2]
topics = [question.split("Write short notes on the anatomy of the ")[1] for question in list_of_questions]
print(topics)
谢谢你,但是,问题之间有文本和空格,没有返回。我该怎么防止呢?我不太明白你的问题。你能举个例子吗?比如:1写一篇关于威利斯环解剖的简短笔记,包括正常变异。2.写关于枢椎(C2椎骨)解剖的简短笔记。我试过这些问题,没有错误。你能说得更具体些吗?给出一个输入,你的输出和期望的输出。由于所有格式都丢失了,所以在注释中写有点困难,但我已经找到了答案。谢谢谢谢你,但是,问题之间有文本和空格,没有返回。我如何防止这种情况发生?如果你能提供一些样本输入,那就太好了。比如:1写一些关于威利斯环解剖的简短笔记,包括正常变异。2写关于枢椎(C2椎骨)解剖的简短笔记。