首页 > 解决方案 > if-else 语句在 for 循环中无法正常运行

问题描述

我正在尝试使用 for 循环中的 if-else 语句计算两个单独字符串中的不同字符。但是,它从不计算不同的字符。

        for char in range(len(f1CurrentLine)):  # Compare line by line
            if f1CurrentLine[char] != f2CurrentLine[char]:  # If the lines have different characters
                print("Unmatched characters: ", count, ":", char)
                diffCharCount = diffCharCount + 1  # add 1 to the difference counter
                count = count + 1
                text1Count = text1Count + len(f1CurrentLine)
                text2Count = text2Count + len(f2CurrentLine)
                return CharByChar(count=count, text2Count=text2Count, text1Count=text1Count,
                                   diffCharCount=diffCharCount)  # return difference count
            else:
                print("Characters matched in line:", count, ". Moving to next line.")
                text1Count = text1Count + len(f1CurrentLine)
                text2Count = text2Count + len(f2CurrentLine)
                count = count + 1
                return CharByChar(count, diffCharCount=diffCharCount, text1Count=text1Count,
                                   text2Count=text2Count,
                                   diffLineCount=diffLineCount)

我有两个文件,其中包含以下内容

文件 1:

1 你好世界

2 炫耀

3 吧台

文件 2:

1 你好世界

2 炫耀

3 富吧

它应该返回 2 个不同的字符,但它没有。如果你想看看我在这里链接的整个函数:Pastebin。希望你能看到我错过的东西。

标签: pythonpython-3.xfile

解决方案


对于这种应用程序,您的代码太复杂了。我已尽力理解代码,并提出了更好的解决方案。

text1 = open("file1.txt")
text2 = open("file2.txt")

# Difference variables
diffLineCount = diffCharCount = line_num = 0


# Iterate through both files line by line
for line1, line2 in zip(text1.readlines(), text2.readlines()): 
    if line1 == "\n" or line2 == "\n": continue # If newline, go to next line
    if len(line1) != len(line2): # If lines are of different length
        diffLineCount += 1
        continue # Go to next line
    for c1, c2 in zip(list(line1.strip()), list(line2.strip())): # Iterate through both lines character by character
        if c1 != c2: # If they do not match
            print("Unmatched characters: ", line_num, ":", c1)
            diffCharCount += 1
    line_num += 1

# Goes back to the beginning of each file
text1.seek(0)
text2.seek(0)

# Prints the stats
print("Number of characters in the first file: ", len(text1.read()))
print("number of characters in the second file: ", len(text2.read()))
print("Number of characters that do not match in lines of the same length: ", diffCharCount)
print("Number of lines that are not the same length: ", diffLineCount)

# Closes the files
text1.close()
text2.close()

我希望您了解它是如何工作的,并且能够使其特别适合您的需求。祝你好运!


推荐阅读