read()
调用都会立即返回空字符串,且指针保持不动——这是 Python 的明文规定。while True:
ch = fi.read(1)
if ch == "": # 文件读完
break
... # 正常处理
fi = open("小女孩.txt","r") ch = "a" dic = {} while ch: ch = fi.read(1) if ch not in ("\n","\r","。","!","?","”",";"): dic[ch] = dic.get(ch,0)+1
这是为什么dic中有{"":1...}的原因
而用for i in str就没问题。for i in txt:
遍历的是已经完整读进内存的字符串,而fi.read(1)
是边读文件边遍历。
fi = open("小女孩.txt","r") fo = open("PY301-1.txt","w") txt = fi.read() d = {} exclude = ",。!?、()【】<>《》=:+-*—“”…" for word in txt: if word in exclude: continue else: d[word] = d.get(word,0)+1