jcpython2 发表于 2022-11-16 22:47:14

一样的代码,结果却不一样

文件a和b功能如下:

终端接收当前目录下两个txt文件,将第一个文件的单词统计写入第二个txt文件中

例:
终端输入
python a.py a1.txt a2.txt

但是结果是a 只能写入第一行,b成功运行全部统计

用vscode对比过ab两个文件代码无任何区别,连空格换行都是一致


以下是a代码
import sys
import re
def countFile(filename,words):
    try:
      f = open(filename,"r",encoding = "gbk" )
    except Exception as e:
      print(e)
      return 0
    txt = f.read()
    f.close()
    splitChars = set([])
    for c in txt:
      if not ( c >= 'a' and c <= 'z' or c >= 'A' and c <= 'Z'):
            splitChars.add(c)
    splitStr = ""
    for c in splitChars:
      if c in {'.','?','!','"',"'",'(',')','|','*','$','\\','[',']','^','{','}'}:
            splitStr += "\\" + c + "|"
      else:
            splitStr +=c + "|"
    splitStr += " "
    lst = re.split(splitStr,txt)
    for x in lst:
      if x == "":
            continue
      lx = x.lower()
      if lx in words:
            words += 1
      else:
            words = 1
      return 1

result = {}
if countFile(sys.argv,result) ==0:
    exit()
lst = list(result.items())
lst.sort()
f = open(sys.argv,"w",encoding="gbk")
for x in lst:
    f.write("%s\t%d\n" % (x,x))
f.close()

以下是b代码
import sys
import re
def countFile(filename,words):
    try:
      f = open(filename,"r",encoding = "gbk" )
    except Exception as e:
      print(e)
      return 0
    txt = f.read()
    f.close()
    splitChars = set([])
    for c in txt:
      if not ( c >= 'a' and c <= 'z' or c >= 'A' and c <= 'Z'):
            splitChars.add(c)
    splitStr = ""
    for c in splitChars:
      if c in {'.','?','!','"',"'",'(',')','|','*','$','\\','[',']','^','{','}'}:
            splitStr += "\\" + c + "|"
      else:
            splitStr +=c + "|"
    splitStr += " "
    lst = re.split(splitStr,txt)
    for x in lst:
      if x == "":
            continue
      lx = x.lower()
      if lx in words:
            words += 1
      else:
            words = 1
    return 1

result = {}
if countFile(sys.argv,result) ==0:
    exit()
lst = list(result.items())
lst.sort()
f = open(sys.argv,"w",encoding="gbk")
for x in lst:
    f.write("%s\t%d\n" % (x,x))
f.close()


附件包含ab文件和例子txt

jackz007 发表于 2022-11-16 23:05:45

【a.py】:
def countFile(filename,words):
. . . . . .
    for x in lst:
. . . . . .
      return 1   # 区别在这一行的缩进位置
【b.py】:
def countFile(filename,words):
. . . . . .
    for x in lst:
. . . . . .
    return 1       # 区别在这一行的缩进位置

jcpython2 发表于 2022-11-16 23:11:06

jackz007 发表于 2022-11-16 23:05
【a.py】:

【b.py】:

牛哦,vscode都检测不出来,竟然没检测缩进,python的缩进很严格呢

wp231957 发表于 2022-11-17 07:17:27

jcpython2 发表于 2022-11-16 23:11
牛哦,vscode都检测不出来,竟然没检测缩进,python的缩进很严格呢

有一种错误叫逻辑错误,这个是任何编辑器也无法检测出来
页: [1]
查看完整版本: 一样的代码,结果却不一样