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

标签 python python-3.x

其他问题似乎没有得到解答,或者没有得到 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/

相关文章:

python - Python TypeError:需要一个整数(元组类型元组)-(OpenCV/Numpy)

python - 在一个函数中获取输入并在另一个函数中调用它

Python贪心算法

python - 同时使用值列表拆分字符串

python - 寻找一种方法来删除重复的答案

python - 在保持值(value)的同时在循环内进行比较

python - 类型错误 : unsupported operand type(s) for -: 'str' and 'int'

python - 将主机系统显示的 HTML+JS 集成到运行在 Docker 容器(linux 子系统)中的 Python 脚本中

coding-style - Python求和式问题

Python 机器学习与音频(预测性维护)