python文本分析基礎小常識報錯處理(十一)

1.Python單字統計分離信息數據報錯

(1)縮進錯誤
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 15:51:26) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>   txt=open("/test.save.data/0000000000001/data.txt").read()
  File "<stdin>", line 1
    txt=open("/test.save.data/0000000000001/data.txt").read()
    ^
IndentationError: unexpected indentZ

以上發生錯誤信息爲:IndentationError: unexpected indent,該錯誤信息參照我之前寫的《Python基礎小常識(十)》得到,該錯誤的意思是IndentationError 縮進錯誤,爲什麼呢?錯誤如下所示:
在這裏插入圖片描述
因此將縮進修改正確,再次運行,又發生了錯誤。

(2)文件不存在錯誤
>>> txt=open("/test.save.data/0000000000001/data.txt").read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '/test.save.data/0000000000001/data.txt'

以上錯誤爲: FileNotFoundError:表示文件不存在,說明路徑錯誤或者文件名稱寫錯了。那重新進行檢查,發現是我路徑和文件名稱都寫錯了。

(3)文件名稱修改後獲取數據
>>> txt=open("C:\\Users\\jhinno\\Desktop\\test.save.data\\0000000000001\\命運.txt").read()
>>>print(txt)

得到文件如下所示:
在這裏插入圖片描述

(4)for循環報錯處理
>>> for  ch  in ",。? : "  :
... txt=txt.replace(ch," " )
  File "<stdin>", line 2
    txt=txt.replace(ch," " )
      ^
IndentationError: expected an indented block

以上錯誤爲 IndentationError: ,通過查找得出IndentationError 縮進錯誤,錯誤了第二次,以上第一次出現過該錯誤。修改後程序正常通過。其中,for結尾需要加冒號,還需要按Tab鍵進行縮進

>>> txt=open("C:\\Users\\jhinno\\Desktop\\test.save.data\\0000000000001\\命運.txt").read()
>>> for  ch  in ",。? : "  :
	txt=txt.replace(ch," " )
(5)標點符號去除處理
txt=txt.replace(ch," " )
(6)最終完整代碼單個字出現頻次的詞頻統計
>>> txt=open("C:\\Users\\jhinno\\Desktop\\test.save.data\\0000000000001\\命運.txt").read()
>>> for  ch  in ",。? : "  :
	txt=txt.replace(ch,"")

	
>>> txt=txt.replace(ch," " )
>>> d={}
>>> for ch in txt:
	d[ch]=d.get(ch,0)+1

	
>>> ls=list(d.items())
>>> ls.sort(key=lambda x:x[1],reverse=True)
>>> a,b=ls[0]
>>> print("{}:{}".format(a,b))
的:2557

2.Python進行單字統計排行前10的信息數據報錯

(1)序列中沒有索引報錯

>>> txt=open("C:\\Users\\jhinno\\Desktop\\test.save.data\\0000000000001\\命運.txt").read()
>>> for ch in txt:
	txt=txt.replace(ch,"")

	
>>> d={}
>>> for ch in txt:
	d[ch]=d.get(ch,0)+1

	
>>> ls=list(d.items())
>>> 
>>> ls.sort(key=lambda x:x[1],reverse=True)
>>> for i in range(10):
	print(str(ls[i])[2],end="")

	
Traceback (most recent call last):
  File "<pyshell#42>", line 2, in <module>
    print(str(ls[i])[2],end="")
IndexError: list index out of range
>>> 

以上報錯信息的原因是:**IndexError 序列中沒有此索引(index),**解決辦法是:for ch in ‘\n’:

>>> txt=open("C:\\Users\\jhinno\\Desktop\\test.save.data\\0000000000001\\命運.txt").read()
>>> for ch in '\n':
	txt=txt.replace(ch,"")

	
>>> d={}
>>> for ch in txt:
	d[ch]=d.get(ch,0)+1

	
>>> ls=list(d.items())
>>> ls.sort(key=lambda x:x[1],reverse=True)
>>> for i in range(10):
	print(str(ls[i])[2],end="")

	
,的"一我了。是不有

因此,逗號使用最多,其次是助詞“的”的使用頻次最高。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章