在python中保持格式的字符串到整数的列表

时间:2023-01-14 16:28:31

So what I want to do seems relatively simple, but for the life of me, I just can't quite get it. I have a .txt file like

所以我想要做的事情似乎相对简单,但对于我的生活,我却无法得到它。我有一个.txt文件

4 2
6 5 1
9 4 5

And I want its information to be available to me like so (i.e. I do not need to write a new .txt file unless it would be necessary.)...

我希望它的信息可以像我这样使用(即我不需要编写新的.txt文件,除非有必要。)...

3 1
5 4 0
8 3 4

or, 1 is subtracted from every number but the formatting remains the same. There will never be a number greater than 1 in the original, so negatives won't be possible. This whole headache is due to converting indexing to begin with 0 instead of 1. What may complicate things is that the original file prints like

或者,从每个数字中减去1,但格式保持不变。原件中永远不会有大于1的数字,因此不可能出现负片。这整个头痛是由于将索引转换为从0而不是1开始。可能使事情变得复杂的是原始文件打印出来的

['4 2 /n','6 5 1 /n', '9 4 5 /n']

What I've Done

我做了什么

Well its a mishmash of different things I've found on *, but I think I'm going about it in the most cumbersome way possible. And this one didn't make sense when I implemented it.. although it may be on the same track with the issue with spaces..

好吧,它是我在*上找到的不同东西的混搭,但我想我会以最繁琐的方式解决它。当我实现它时,这个没有意义..虽然它可能与空格问题在同一轨道上..

origianl = open(file, 'r')
for line in original.readlines():
    newline = line.replace(" \n","")
    finalWithStrings.append(newline)

finalWithIntegers = [map(int,x) for x in finalWithStrings]
finalWithIntegers[:] = [x-1 for x in finalWithIntegers]

My thought process was, I need to remove the "/n" and to convert these strings into integers so I can subtract 1 from them. And somehow keep the formatting. It's important to have the formatting be the same since each line contains information on the similarly indexed line of another file. I don't want to see the "/n" in the end result (or print statement) but I still want the effect of a new line beginning. The above code however, wont work for two reasons (that I know of).

我的思维过程是,我需要删除“/ n”并将这些字符串转换为整数,这样我就可以从中减去1。并以某种方式保持格式。格式化是很重要的,因为每行包含有关另一个文件的类似索引行的信息。我不想在最终结果(或打印语句)中看到“/ n”但我仍然希望新行的效果开始。但是上面的代码不会有两个原因(我知道)。

int(n[:]) throws an error since it doesn't like the spaces and when I put a value (say 0) in there, then the code prints the first number on each of the lines and subtracts one.. and puts it all on one line.

int(n [:])抛出一个错误,因为它不喜欢空格,当我在那里放一个值(比如0)时,代码打印每行上的第一个数字并减去一个..并且放置一切都在一条线上。

[3, 5, 8]

So, it seems redundant to take out a carriage return and have to throw another in, but I do need to keep the formatting, as well as have a way to get all the numbers!

因此,取出回车并且必须抛出另一个回车似乎是多余的,但我确实需要保持格式化,并且有办法获得所有数字!

This also didn't work:

这也行不通:

for line in original.readlines():
    newline = line.replace(" \n","")
    finalWithStrings.append(newline)

finalWithIntegers = [map(int,x) for x in finalWithStrings]
finalWithIntegers[:] = [x-1 for x in finalWithIntegers]    

but instead of just a wrong output it was an error:

但不是只是一个错误的输出,这是一个错误:

ValueError:invalid literal for int() with base 10:''

Does anyone have any ideas on what I'm doing wrong here and how to fix this? I am working with Python 2.6 and am a beginner.

有没有人对我在这里做错了什么以及如何解决这个问题有任何想法?我正在使用Python 2.6并且是初学者。

4 个解决方案

#1


9  

with open("original_filename") as original:
    for line in original:
        #if you just want the line as integers:
        integers = [ int(i) - 1 for i in line.split() ]
        #do something with integers here ...

        #if you want to write a new file, use the code below:
        #new_line = " ".join([ str(int(i) - 1) for i in line.split() ])
        #newfile.write(new_line + '\n')

I've opened your file in a context manager in the above example because that is good practice (since version 2.5). The context manager makes sure that your file is properly closed when you exit that context.

我在上面的例子中在上下文管理器中打开了你的文件,因为这是一个很好的做法(从版本2.5开始)。当您退出该上下文时,上下文管理器会确保您的文件已正确关闭。

EDIT

It looks like you might be trying to create a 2D list ... To do that, something like this would work:

看起来你可能正在尝试创建一个2D列表......要做到这一点,这样的事情会起作用:

data = []
with open("original_filename") as original:
    for line in original:
        integers = [ int(i) - 1 for i in line.split() ]
        data.append(integers)

Or, if you prefer the 1-liner (I don't):

或者,如果您更喜欢1-liner(我没有):

with open("original_filename") as original:
    data = [ [int(i) for i in line.split()] for line in original ]

Now if you print it:

现在,如果你打印它:

for lst in data:
    print (lst)    # [3, 1]
                   # [5, 4, 0]
                   # [8, 3, 4]

#2


4  

Here is a pretty straight forward way to accomplish this using regular expressions. The benefit here is that the formatting is guaranteed to stay exactly the same because it will replace the numbers in place without touching any of the whitespace:

这是使用正则表达式实现此目的的一种非常直接的方法。这里的好处是格式保证保持完全相同,因为它将替换现有的数字而不触及任何空格:

import re

def sub_one_repl(match):
    return str(int(match.group(0))-1)

for line in original.readlines():
    newline = re.sub(r'\d+', sub_one_repl, line).rstrip('\n')

#3


2  

Another way is to use the csv module and list comprehension:

另一种方法是使用csv模块和列表理解:

from csv import reader

data = [[int(j) - 1 for j in i] for i in reader(open("your_file"), delimiter=' ')]

It results, for example, using your data:

例如,它会导致使用您的数据:

[[3, 1], [5, 4, 0], [8, 3, 4]]

#4


0  

Try this:

with open(filepath) as f:
    for line in f:
        print " ".join([str(int(i)-1) for i in line.split()])

Hope that helps

希望有所帮助

#1


9  

with open("original_filename") as original:
    for line in original:
        #if you just want the line as integers:
        integers = [ int(i) - 1 for i in line.split() ]
        #do something with integers here ...

        #if you want to write a new file, use the code below:
        #new_line = " ".join([ str(int(i) - 1) for i in line.split() ])
        #newfile.write(new_line + '\n')

I've opened your file in a context manager in the above example because that is good practice (since version 2.5). The context manager makes sure that your file is properly closed when you exit that context.

我在上面的例子中在上下文管理器中打开了你的文件,因为这是一个很好的做法(从版本2.5开始)。当您退出该上下文时,上下文管理器会确保您的文件已正确关闭。

EDIT

It looks like you might be trying to create a 2D list ... To do that, something like this would work:

看起来你可能正在尝试创建一个2D列表......要做到这一点,这样的事情会起作用:

data = []
with open("original_filename") as original:
    for line in original:
        integers = [ int(i) - 1 for i in line.split() ]
        data.append(integers)

Or, if you prefer the 1-liner (I don't):

或者,如果您更喜欢1-liner(我没有):

with open("original_filename") as original:
    data = [ [int(i) for i in line.split()] for line in original ]

Now if you print it:

现在,如果你打印它:

for lst in data:
    print (lst)    # [3, 1]
                   # [5, 4, 0]
                   # [8, 3, 4]

#2


4  

Here is a pretty straight forward way to accomplish this using regular expressions. The benefit here is that the formatting is guaranteed to stay exactly the same because it will replace the numbers in place without touching any of the whitespace:

这是使用正则表达式实现此目的的一种非常直接的方法。这里的好处是格式保证保持完全相同,因为它将替换现有的数字而不触及任何空格:

import re

def sub_one_repl(match):
    return str(int(match.group(0))-1)

for line in original.readlines():
    newline = re.sub(r'\d+', sub_one_repl, line).rstrip('\n')

#3


2  

Another way is to use the csv module and list comprehension:

另一种方法是使用csv模块和列表理解:

from csv import reader

data = [[int(j) - 1 for j in i] for i in reader(open("your_file"), delimiter=' ')]

It results, for example, using your data:

例如,它会导致使用您的数据:

[[3, 1], [5, 4, 0], [8, 3, 4]]

#4


0  

Try this:

with open(filepath) as f:
    for line in f:
        print " ".join([str(int(i)-1) for i in line.split()])

Hope that helps

希望有所帮助