gpt4 book ai didi

python - 如何读取文本文件的特定部分 (Py 3x)

转载 作者:太空宇宙 更新时间:2023-11-03 20:55:58 25 4
gpt4 key购买 nike

其他问题似乎没有得到解答,或者没有得到 Python 的答案。我试图让它找到关键字“name”,将位置设置到那里,然后将变量设置为该特定行,然后让它仅使用该文本片段作为变量。简而言之,我试图根据始终存在的“名称”或“HP”在 .txt 文件中查找变量。

我希望这是有道理的......

我尝试使用不同的变量,例如 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 也是如此,但不打印 nameHP本身。

所以它应该只是打印

Wubzy
100
Press any key to continue . . .

但它反而打印

Wubzy


Press any key to continue . . .

最佳答案

对于 regex 来说,这看起来是一份不错的工作。 。正则表达式可以匹配和捕获文本中的模式,这似乎正是您想要做的。

例如,正则表达式 ^name\s*=\s*(\w+)$ 将匹配具有确切文本“name”、后跟 0 个或多个空白字符、 '=',然后是另外 0 个或多个空白字符,然后是一个或多个字母。它将捕获最后的词组。

正则表达式 ^HP\s*=\s*(\d+)$ 将匹配包含确切文本“HP”、后跟 0 个或多个空白字符、“=”的行,然后是另外 0 个或多个空白字符,然后是一个或多个数字。它将捕获最后的数字组。


# This is the regex library
import re

# This might be easier to use if you're getting more information in the future.
reg_dict = {
"name": re.compile(r"^name\s*=\s*(\w+)$"),
"HP": re.compile(r"^HP\s*=\s*(\d+)$")
}


def savetest():
save = open("nametest_text.txt", "r")
print("Do you have a save?")
conf = input(": ")
# instead of checking each one individually, you can check if conf is
# within a much smaller set of valid answers
if conf.lower() in ["y", "yes"]:
text = save.read()

# Find the name
match = reg_dict["name"].search(text)
# .search will return the first match of the text, or if there are
# no occurrences, None
if(match):
# With match groups, group(0) is the entire match, group(1) is
# What was captured in the first set of parenthesis
username = match.group(1)
else:
print("The text file does not contain a username.")
return
print(username)

# Find the HP
match = reg_dict["HP"].search(text)
if(match):
player_hp = match.group(1)
else:
print("The text file does not contain a HP.")
return
print(player_hp)

# Using system calls to pause output is not a great idea for a
# variety of reasons, such as cross OS compatibility
# Instead of os.system("pause") try
input("Press enter to continue...")

save.close()
savetest()

关于python - 如何读取文本文件的特定部分 (Py 3x),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56027892/

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