python - 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。希望你能看到我错过的东西。
解决方案
对于这种应用程序,您的代码太复杂了。我已尽力理解代码,并提出了更好的解决方案。
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()
我希望您了解它是如何工作的,并且能够使其特别适合您的需求。祝你好运!
推荐阅读
- java - How let loop of buttons comunicate to each other
- c# - How can I save a captured picture from the user to the cosmos db in xamarin forms?
- reactjs - 即使在重新加载选项后,下拉列表的选定值仍然存在
- sql - SQL 在一段时间后重新初始化值
- reactjs - React slick doesn't loop slides if slidesToShow is equal to the total slides
- php - SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens...but it does?
- ios - How can I debug EXC_BAD_ACC (code=2, address=xxx)?
- android - Android menu icon size, i dont know how to change it
- sql - 当我加入最终表时数据消失 - SQL
- neo4j - Neo4j 嵌套 XML 文件加载