Python:如何在不使用.split

问题描述 投票:0回答:2

这是我尝试在文件号码中读取的代码

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等于空间时该怎么办,因为在否定功能中无法否定空间

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

根据教师的指示,我不允许使用以外的任何字符串方法。我无法在此任务中使用.split,因为这将变得非常容易。任何帮助或旅行都将不胜感激,我已经完成了几天的工作,现在我似乎无法实现它的工作。
	

本代码在您提供的测试输入中正常工作:

python file io
2个回答
2
投票
您可以自己添加IF语句。另外,如果您只想打印它,则无需将INT转换为STR。

也许还有另一种方式
,而不是进行大量计算,而是始终产生相同的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()

1
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.