简体   繁体   English

读取文本文件并将一些字符放入列表

[英]reading text file and putting some characters in lists

My objective is to transform this text in a textfile (all in 1 line): 我的目标是将此文本转换为文本文件(全部在1行中):

a b s d p
5 4 3 3 2
..........
....pp..s.
........s.
.a......s.
.a.....b..
.a.....b..
.a.....b..
.a.ddd.b..
..........
..........

And have an output: [['a', 'b', 's', 'd', 'p'],[5, 4, 3, 3, 2]] But I get the following error: ship_characters.append(str(char)) MemoryError 并有一个输出:[['a','b','s','d','p'],[5,4,3,3,2]]但是我得到以下错误:ship_characters.append (str(字符))MemoryError

Here is my code: 这是我的代码:

def read_ship_data(game_file):

    ship_characters = []
    ship_sizes = []

    game = open(game_file, 'r')
    for line in game:
        for char in line:
            while char != '.':
                if char.isalpha():
                    ship_characters.append(str(char))
                elif char.isnumeric():
                    ship_sizes.append(int(char))
    return [ship_characters , ship_sizes]

Right now, you are looping infinitely on the first character and appending it to your list. 现在,您正在第一个字符上无限循环,并将其附加到列表中。 Your while loop will never stop since 'a' != '.' 您的while循环永远不会停止,因为'a' != '.' will always be true. 永远是真的。

If you just want the 2 first lines and the format will never change, you should use something simpler: 如果只希望前两行并且格式永远不会改变,则应该使用更简单的方法:

def read_ship_data(game_file):
    with open(game_file, 'r') as file:
        ship_characters = file.readline().strip().split()
        ship_sizes = file.readline().strip().split()
        ship_sizes = [int(i) for i in ship_sizes]

    return [ship_characters, ship_sizes]

You're looping forever: 你永远循环:

for char in line:
    while char != '.':
        if char.isalpha():
            ship_characters.append(str(char))
        elif char.isnumeric():
            ship_sizes.append(int(char))

You set the value of char for one iteration through line , then you stay in your while loop as long as that value isn't '.' 您通过line设置char的值进行一次迭代,然后只要该值不是'.' ,就停留在while循环中'.' - but no where in the while loop do you change the value of char . -但是在while循环中的任何地方都不会更改char的值。 That happens outside of the while loop, when it gets to the next cycle in the for loop. 当到达for循环中的下一个循环时,这会在while循环之外发生。

It seems like you want to remove the while loop and instead have if char != '.': maybe? 似乎您想删除while循环,而是使用if char != '.':也许吗?

Edit: Actually there's no need to catch '.' 编辑:实际上没有必要捕捉'.' separately - you're already testing using isalpha() and isnumeric() - note that you want isdigit() if you're in Python 2.x and not using unicode - and a '.' 分别-您已经在使用isalpha()isnumeric() -请注意,如果您使用的是Python 2.x而未使用unicode,则需要isdigit() -和'.' returns False on both of those. 两者都返回False。 So you can do it like this: 因此,您可以这样做:

for char in line:
    if char.isalpha():
        ship_characters.append(str(char))
    elif char.isnumeric():
        ship_sizes.append(int(char))
    else:
        pass
        #do something for non-letter and non-number values if you want

Others have identified the reason for the memory error: an infinite loop. 其他人已经确定了内存错误的原因:无限循环。

Assuming that you require the first 2 lines from the file here is a better way to do it: 假设您需要文件的前两行是一种更好的方法:

def read_ship_data(game_file):
    with open(game_file) as game_file:
        return [line.split() for line in (next(game_file), next(game_file))]

This just reads the first 2 lines from the file (with next(file) ), and splits the lines in a list comprehension, which is returned from the function. 这仅从文件中读取前两行(带有next(file) ),并以列表推导方式拆分行,该列表推导从函数返回。

If you need to convert the values from the second line to integers: 如果需要将第二行中的值转换为整数:

def read_ship_data(game_file):
    with open(game_file) as game_file:
        return [next(game_file).split(),  [int(x) for x in next(game_file).split()]]

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM