对于Python来说,其他问题似乎没有得到回答或者没有得到回答。我试图让它找到关键字“name”,将位置设置为there,然后将一个变量设置为特定的行,然后让它只使用这段文本作为变量。简而言之,我试图在.txt文件中找到一个基于“name”或“HP”的变量,它将一直存在。你知道吗
我希望这有道理。。。你知道吗
我尝试过使用不同的变量,比如currentplace
,而不是namePlace
,但两者都不起作用。你知道吗
import os
def savetest():
save = open("nametest_text.txt", "r")
print("Do you have a save?")
conf = input(": ")
if conf == "y" or conf == "Y" or conf == "Yes" or conf == "yes":
text = save.read()
namePlace = text.find("name")
currentText = namePlace + 7
save.seek(namePlace)
nameLine = save.readline()
username = nameLine[currentText:len(nameLine)]
print(username)
hpPlace = text.find("HP")
currentText = hpPlace + 5
save.seek(hpPlace)
hpLine = save.readline()
playerHP = hpLine[currentText:len(hpLine)]
print(playerHP)
os.system("pause")
save.close()
savetest()
我的文本文件很简单:
name = Wubzy
HP = 100
我想让它打印出在name
和HP
等号后面的内容,而不是name
和HP
本身。你知道吗
所以应该打印出来
Wubzy
100
Press any key to continue . . .
但它会打印出来
Wubzy
Press any key to continue . . .
对于一个regex来说,这看起来是个不错的工作。正则表达式可以匹配和捕获文本中的模式,这似乎正是您要做的。你知道吗
例如,regex
^name\s*=\s*(\w+)$
将匹配具有确切文本“name”的行,后跟0个或多个空格字符、一个“=”,然后是另外0个或多个空格字符,然后是一个或多个字母。它将在结尾捕获单词组。你知道吗正则表达式
^HP\s*=\s*(\d+)$
将匹配具有精确文本“HP”的行,后跟0个或多个空格字符、一个“=”,然后是另一个0个或多个空格字符,然后是一个或多个数字。它将在最后捕获数字组。你知道吗最简单的方法可能是使用^{} ,然后打印
'='
字符后面的所有内容:输出:
使用正则表达式根据模式进行提取:
它捕获任何跟在等号后面,前面有
name
或HP
的内容。你知道吗代码:
相关问题 更多 >
编程相关推荐