简体   繁体   English

将文本文件中的行附加到列表中时,会将整行设置为字符串。 如何识别文本文件中的不同数据类型?

[英]When appending lines from a text file into a list, it sets the whole line to a string. How do I recognise different data types inside a text file?

I am making a Pokémon game using Python 3.7.0 and I am making a save/load function using text documents.我正在使用 Python 3.7.0 制作 Pokémon 游戏,并且正在使用文本文档制作保存/加载功能。 Each line inside the text file holds a string and an integer and I was wondering if there was a way to recognise that those data types already exist and append them to the list while keeping the type.文本文件中的每一行都包含一个字符串和一个整数,我想知道是否有办法识别这些数据类型已经存在并将它们附加到列表中,同时保留类型。

A sub issue that is cause by this is that each character in the index is treated as a separate index, rather than each part separated by the comma.由此导致的一个子问题是索引中的每个字符都被视为一个单独的索引,而不是每个部分用逗号分隔。

I've tried splitting each data type on a separate line and appending each one separately, then checking if it contains quotations or not but that just leaves me with the same result that I've been getting.我尝试将每种数据类型拆分为单独的一行并分别附加,然后检查它是否包含引号,但这只会让我得到与我得到的结果相同的结果。

Each line in the text files appears like this ('name',level):文本文件中的每一行显示如下('name',level):

'charmander',12

'bulbasaur',7

'squirtle',13

My code to load the file into a list is as follows:我将文件加载到列表中的代码如下:

path, dirs, files = next(os.walk("resources/saves")) # Read directory
fileCount = len(files)
while fileCount > 0:
    for filename in os.listdir("resources/saves"): # Iterates directory
    fileCount -= 1
    loadFile = open("resources/saves/%s" % (filename),"r")
    pokeCount = 6
    for line in loadFile:
        if pokeCount > 0:
            party.append(line.split()) # Adds first six Pokémon to the party
            pokeCount -= 1
        else:
            pc.append(line.split()) # Adds rest to the PC
            print("Game loaded!")

After getting the output below, I tried:得到下面的输出后,我试过:

for i in party:
    for j in i:
        j.replace('\"','')
        print(j) # Test if each part is treated as an index

However I got each character printed on a new line, as if each one was a new index, rather than the name and level be treated as two separate indexes.但是我将每个字符打印在新行上,就好像每个字符都是一个新索引,而不是将名称和级别视为两个单独的索引。

I expect the appended list to look like this:我希望附加列表如下所示:

[['charmander',12],['bulbasaur,7],['squirtle',13]]

However the list I get is:但是我得到的清单是:

[["'charmander','12'"],["'bulbasaur,'7'"],["'squirtle','13'"]]

The numbers are being treated as strings, then the whole index is being treated as a superior string.数字被视为字符串,然后整个索引被视为上级字符串。 I would like to have the name treated as a string in the first index of the sub-list, and the level treated as an integer in the second index of the sub-list.我希望在子列表的第一个索引中将名称视为字符串,而在子列表的第二个索引中将级别视为整数。

Thanks to anyone who can understand this and who can help!感谢任何能理解这一点并能提供帮助的人!

You do not need to use a counter, simply check the length of the produces list - if it reaches 6 stop parsing the file.您不需要使用计数器,只需检查产品列表的长度 - 如果达到 6 则停止解析文件。

You need to split each line of your file at , and convert the level back to a number - you read strings from your file:您需要将文件的每一行拆分为,并将级别转换回数字 - 您从文件中读取字符串:

Create file:创建文件:

t = """
'charmander',12

'bulbasaur',7

'squirtle',13"""

Read and process file:读取和处理文件:

with open("data.txt","w") as f: 
    f.write(t)

pokemons = []

with open("data.txt") as f:
    for line in f:          
        line = line.strip() # remove \n and other whitespaces
        if line:            # only process non empty lines
            try:
                poke, lvl = line.split(",")
            except ValueError:
                print("Unable to split line into 2 parts: ", line)
                continue

            try:
                lvl = int(lvl)                       # convert to int
            except ValueError:
                print("Unable to convert lvl to number: ", lvl)
                continue

            poke = poke.strip("'")               # get rid of the delimiting '

            # add to list of pokemons when all was ok   
            pokemons.append( [poke,lvl] )

        if len(pokemons) ==  6:
            break

print(pokemons) 

Output:输出:

[['charmander', 12], ['bulbasaur', 7], ['squirtle', 13]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我来自 csv 文件的文本被读取为原始字符串。 它包含“it\'s”而不是 it's。 我该如何清洁这个? - My text from csv file is being read as raw string. It contains “it\'s” instead of it's. How do I clean this? 从Python的文本文件中读取包含文本字符串的整行 - Reading a whole line containing a text string from a text file in Python 如何从文本文件中获取数据集到列表和变量中? - How do I get data sets from text file in to lists and variables? 如何将数据从文本文件转换为列表? - How do I turn data from a text file into a list? 如何逐行读取文本文件并从文件内容中返回两个字符串和一个列表? - How do I read a text file line by line and return two strings and a list from the contents of the file? 在 Python 中的文本文件的特定行中附加数据? - appending a data in a specific line of a text file in Python? 在文件Python中的特定文本行中附加数据 - Appending Data In a Specific Line of Text in a File Python 如何在文本文件的排序二维列表中打印 3 种不同类型的值? - How can I print 3 different types of values in a sorted 2d list from a text file? 从文件内的字符串将列表附加到列表中 - appending list in a list from string inside the file 如果我有一个字典,其中行的键和内容是文本,如何轻松地将行写入文本文件? - How do I write lines to a text file easily if I have a dictionary with the key of the line and contents being the text?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM