gpt4 book ai didi

python - 如何在某个未知索引处对字符串输入进行切片

转载 作者:太空狗 更新时间:2023-10-29 17:28:30 25 4
gpt4 key购买 nike

一个字符串作为输入(例如“你叫什么名字?”)。输入 always 包含我要提取的问题。但是我要解决的问题是输入总是带有不需要的输入。

因此输入可以是(但不限于)以下内容:

1- "eo000 ATATAT EG\n\n你叫什么名字?\nkgda dasflkjasn"2- "你的\n姓氏和电子邮件是什么?\ndasf?lkjas"3- "askjdmk。\n鉴于你的技能\n你如何评价自己?\n你的名字是什么?dasf?”

(请注意,在第三个输入中,问题以单词“Given”开头,以“yourself?”结尾)

以上输入示例由pytesseract OCR库扫描图片转文本生成

只是想从垃圾输入中提取问题,没有别的。

我尝试使用re 库find('?', 1) 函数来获取问题最后一部分的索引(目前假设第一个问号始终是问题的结尾,而不是我不想要的输入的一部分)。但是我不知道如何获取问题第一个字母的索引。我尝试反向循环并在输入中找到第一个\n,但问题并不总是在问题的第一个字母之前有\n。

def extractQuestion(q):
index_end_q = q.find('?', 1)
index_first_letter_of_q = 0 # TODO
question = '\n ' . join(q[index_first_letter_of_q :index_end_q ])

最佳答案

查找问题第一个单词索引的方法是搜索具有实际含义的第一个单词(我想您对英语单词感兴趣)。一种方法是使用 pyenchant :

#!/usr/bin/env python

import enchant

GLOSSARY = enchant.Dict("en_US")

def isWord(word):
return True if GLOSSARY.check(word) else False

sentences = [
"eo000 ATATAT EG\n\nWhat is your name?\nkgda dasflkjasn",
"What is your\nlastname and email?\ndasf?lkjas",
"\nGiven your skills\nhow would you rate yourself?\nand your name? dasf?"]

for sentence in sentences:
for i,w in enumerate(sentence.split()):
if isWord(w):
print('index: {} => {}'.format(i, w))
break

上面的代码给出了结果:

index: 3 => What
index: 0 => What
index: 0 => Given

关于python - 如何在某个未知索引处对字符串输入进行切片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56912823/

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