无法使我的代码识别特定字符串

2024-06-26 00:14:05 发布

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

我在为学校的一个小项目编写代码。我想读一个.txt文件,找出“pergunta[]”和一个问号之间的关系,但我的程序无法给出这个。你知道吗

我已经尝试过有人建议的here,但它似乎对我不起作用,因为它无法检索我想要的字符串片段,而且显然甚至没有输入if语句。你知道吗

(“perguntas”指问题)

import pyttsx3

speak = pyttsx3.init()

running = True
perguntas = open(r"C:\Users\jeana\Desktop\perguntas.txt", "r")
texto = perguntas.read()

while running:
    if "pergunta5 " in texto:
        data = texto.split("pergunta5 ")[1].split("?")[0]
        print(data) #tried adding this line but it is never printed
        speak.say(data)
        speak.runAndWait()
        running = False
    print("um loop") #I added this just to know the code reaches this point
    running = False

我希望我的代码能找到介于“pergunta[]”(本例中是5,只是为了简化)和“?”之间的问题但是由于某些原因,这段代码只是输出一些听起来像“p”的东西,并且没有错误消息。我想知道我是否遗漏了一些基本的东西。。。你知道吗

文本文件如下所示:

pergunta1 Quanto é dois mais dois? R: 4 - 2
pergunta2 Quanto é cinco menos 2? R: 3 - 2
pergunta3 Quanto é cinco menos 1? R: 4 - 2
pergunta4 A peppa pig é um? R: Porco - 3
pergunta5 Qual a cor do cavalo branco do napoleão? R: Branco - 3

编辑: 我的代码更简单的版本是

text = "a lot of text with some question1 yadayadayada? question2 dayadayadaya?"
if "question1" in text:
    data = text.split("question1")[1].split("?")[0]
    print(data)

输出应该是:

yadayadayada

Tags: 代码texttxtdataifthisrunningsplit
2条回答

使用内置的方法“with”来读取文件,正则表达式是用来拆分语句“pergunta”的。这里“.”表示任何东西。有关更多说明,请参阅python的regex。你知道吗

import re
with open('perguntas.txt','r') as f:
     content = f.read()

sp = re.split('pergunta.', content)
print(sp)

原来@JohnGordon让我看到了问题所在。代码本身没有问题,但是.txt文件有更多的编码。我所做的只是简单地将所有文本粘贴到代码中的一个字符串中,效果很好。你知道吗

相关问题 更多 >