Python:如何在不使用.spli的情况下读取和更改文件中的多个数字

2024-06-26 13:37:27 发布

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

这是我用来读取文件编号的代码

def process_body(infile, outfile, modification):
'''
changing the numbers to the outfile              
'''

for line in infile.readlines():
    line = line.strip()
    num = ""
    space = " "

    if modification == "negate": 
        for char in line:
            input() #The file is really big this is here to go line by line for decoding
            if char != space:
                num += char

            neg = negate(num)
            print(neg)

            if char == space:
                pass

当char等于space时,我不确定该怎么办,因为在negate函数中不能对space求反

def negate(num):
'''
absolute value of RGB value - 255
'''

num = int(num)
negate_line = num - 255
negate_line = abs(negate_line)
negate_line = str(negate_line)
return negate_line

下面是输入文件中的几行

0 44 89 0 44 89 0 44 89 0 44 89 1 45 90 
1 45 90 1 45 90 1 45 90 1 45 92 1 45 92 
1 45 92 0 46 92 0 46 92 0 47 93 0 47 93 

根据老师的指示,除了.strip以外,我不会大声使用任何字符串方法。我不能在这个作业中使用.split,因为它会使作业变得非常简单。任何帮助或旅行将不胜感激,我已经在这个任务几天了,现在我似乎不能得到它相当的工作。你知道吗


Tags: 文件thetoinforifdefline
2条回答

也许还有另一种方法,不是做大量的计算,总是会产生相同的256个不同的结果,而是对所有的计算做一次。有时候,当你被困在一个问题上时,把它倒过来,换个方向去做。你知道吗

def main():
    converter = {str(x): str(abs(x-255)) for x in range(256)}
    s = ["0 44 89 0 44 89 0 44 89 0 44 89 1 45 90",
         "1 45 90 1 45 90 1 45 90 1 45 92 1 45 92",
         "1 45 92 0 46 92 0 46 92 0 47 93 0 47 93"]

    for line in s:
        num = ""
        new_line = []
        for c in line:
            if c == " ":
                new_line += [converter[num]]
                num = ""
            else:
                num += c

        print(" ".join(new_line))

if __name__ == '__main__':
    main()

此代码在您提供的测试输入上运行良好:

with open('ip', 'rb') as f:
  for line in f:
    char = ""
    for c in line.strip():
      if c != " ":
        char += c
      else:
        print abs(int(char) - 255)
        char = ""

您可以自己添加if语句。另外,如果只想打印int,则不需要将其转换为str。你知道吗

相关问题 更多 >