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

2024-10-01 13:42:45 发布

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

对于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

我想让它打印出在nameHP等号后面的内容,而不是nameHP本身。你知道吗

所以应该打印出来

Wubzy
100
Press any key to continue . . .

但它会打印出来

Wubzy


Press any key to continue . . .

Tags: ortextnametxtossaveconfhp
3条回答

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

例如,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()

最简单的方法可能是使用^{},然后打印'='字符后面的所有内容:

with open("nametest_text.txt", "r") as f:    
    for line in f:
        if line.strip():
            print(line.strip().split(' = ')[1])

输出:

Wubzy
100

使用正则表达式根据模式进行提取:

'(?:name|HP) = (.*)'

它捕获任何跟在等号后面,前面有nameHP的内容。你知道吗

代码

import re

with open("nametest_text.txt", "r") as f:    
    for line in f:
        m = re.search(r'(?:name|HP) = (.*)', line.strip())
        if m:
            print(m.group(1))

相关问题 更多 >