用python處理文字資料
實驗目的
熟悉python的基本資料結構,以及檔案的輸入與輸出。
實驗數據
利用xxxx年xx機器學習會議的評測資料和評測任務,資料包括訓練集和測試集,評測任務為通過給定的訓練數據,預測測試集中的關係是正例還是負例,在每個樣本最後給出1或0。
資料描述如下,第一列為關係類型,第二列和第三列為人名,第四列是標題,第五列是關係為正例還是負例,1為正例, 0為負例;第六列表示訓練集。
事件 | 人物1 | 人物2 | 標題 | 關係(0 or 1 ) | 訓練集 |
---|
測試集描述如下圖,格式基本上與訓練集類似,唯一不同的是第五列沒有關係是正例還是負例的標記。
關係 | 人物1 | 人物2 | 事件 |
---|
實驗內容
對訓練集資料進行處理,只留下前面五列,輸出文字命名為exp1_1.txt。
在第一步驟得到的資料的基礎上對19類關係進行分類,產生的文字存放在exp1_train資料夾下,依照關係類別出現的順序,第一個關係類別的資料存放在1 .txt中,第二個關係類別存放在2.txt中,直到19.txt。
測試集依照訓練集的19個類別的順序將各個樣本依照關係類別歸類,即相同關係類型的資料放到一個文字檔案中,同樣產生19個類別的測試文件,格式仍舊和測試文件保持一致。存放在exp1_test資料夾下,每個類別的檔案仍舊命名為1_test.txt,2_test.txt…同時對每個樣本在原測試集中出現的位置進行記錄,和19個測試檔案一一對應起來。例如第一類「傳聞不和」的每個樣本在原文中處於第幾行,在索引檔中進行記錄,保存在檔案index1.txt,index2.txt….
解題思路
1.第一題是考察我們文件操作與列表的知識,主要考察的難題是對new文件的讀取,根據要求處理後在生成一個txt文件,讓我們看一下具體的程式碼實作:
import os # 创建一个列表用来存储新的内容 list = [] with open("task1.trainSentence.new", "r",encoding='xxx') as file_input: # 打开.new文件,xxx根据自己的编码格式填写 with open("exp1_1.txt", "w", encoding='xxx') as file_output: # 打开exp1_1.txt,xxx根据自己的编码格式填写文件如果没有就创建一个 for Line in file_input: # 遍历每一行的文件 arr = Line.split('\t') # 以\t为分隔符读取 if arr[0] not in list: # if the word is not in the list list.append(arr[0]) # add the word to the list file_output.write(arr[0]+"\t"+arr[1]+"\t"+arr[2]+"\t"+arr[3]+"\t"+arr[4]+"\n") # write the line to the file file_input.close() #关闭.new文件 file_output.close() #关闭创建的txt文件
2.第二題依舊考察了文件操作,在題目一生成的文件基礎上,按照同一類型的事件對事件進行分類,是否能高效的分組需要利用循環條件來解決,我們來看看具體的
代碼實現
import os file_1 = open("exp1_1.txt", encoding='xxx') # 打开文件,xxx根据自己的编码格式填写 os.mkdir("exp1_train") # 创建目录 os.chdir("exp1_train") # 修改进程的工作目录(使用该目录) a = file.readline() # 按行读取exp1_1.txt文件 arr = a.split("\t") # 按\t间隔符作为分割 b = 1 #设置分组文件的序列 file_2 = open("{}.txt".format(b), "w", encoding="xxx") # 打开文件,xxx根据自己的编码格式填写 for line in file_1: # 按行读取文件 arr_1 = line.split("\t") # 按\t间隔符作为分割 if arr[0] != arr_1[0]: # 如果读取文件的第一列内容与存入新文件的第一列类型不同 file_2.close() # 关掉该文件 b += 1 # 文件序列加一 f_2 = open("{}.txt".format(b), "w", encoding="xxx") # 创建新文件,以另一种类型分类,xxx根据自己的编码格式填写 arr = line.split("\t") # 按\t间隔符作为分割 f_2.write(arr[0]+"\t"+arr[1]+"\t"+arr[2]+"\t"+arr[3]+"t"+arr[4]+"\t""\n") # 将相同类型的文件写入 f_1.close() # 关闭题目一创建的exp1_1.txt文件 f_2.close() # 关闭创建的最后一个类型的文件
3.將訓練集的19個類別按照人物的關係進行進一步的分類,我們可以透過字典對資料進行遍歷,查找關係,把關係相同的內容放到一個資料夾中,不同則新建一個。
import os with open("exp1_1.txt", encoding='xxx') as file_in1: # 打开文件,xxx根据自己的编码格式填写 i = 1 # 类型序列 arr2 = {} # 创建字典 for line in file_in1: # 按行遍历 arr3 = line[0:2] # 读取关系 if arr3 not in arr2.keys(): arr2[arr3] = i i += 1 # 类型+1 file_in = open("task1.test.new") # 打开文件task1.test.new os.mkdir("exp1_test") # 创建目录 os.chdir("exp1_test") # 修改进程的工作目录(使用该目录) for line in file_in: arr = line[0:2] with open("{}_test.txt".format(arr2[arr]), "a", encoding='xxx') as file_out: arr = line.split('\t') file_out.write(line) i = 1 file_in.seek(0) os.mkdir("exp1_index") os.chdir("exp1_index") for line in file_in: arr = line[0:2] with open("index{}.txt".format(arr2[arr]), "a", encoding='xxx') as file_out: arr = line.split('\t') line = line[0:-1] file_out.write(line + '\t' + "{}".format(i) + "\n") i += 1
用python處理數值型資料
實驗目的
熟悉python的基本資料結構,以及檔案的輸入與輸出。
實驗數據
xxxx年xx天池大賽,也是中國大學第x屆大數據挑戰賽的數據。資料包含兩個表,分別是使用者行為表mars_tianchi_user_actions.csv和歌曲藝人表mars_tianchi_songs.csv。大賽開放抽樣的歌曲藝人數據,以及和這些藝人相關的6個月內(20150301-20150831)的用戶行為歷史記錄。選手需預測藝人隨後2個月,也就是60天(20150901-20151030)的播放資料。
#實驗內容
-
對歌曲藝人資料mars_tianchi_songs進行處理,統計出藝人的數量以及每個藝人的歌曲數量。輸出檔案格式為exp2_1.csv,第一列為藝人的ID,第二列為該藝人的歌曲數目。最後一行輸出藝人的個數。
將使用者行為表和歌曲藝人表以歌曲song_id作為關聯,合併為一個大表。各列名稱為第一到第五列與使用者行為表的列名一致,第六到第十列為歌曲藝人表中的第二列到第六列的列名。輸出檔名為exp2_2.csv。
依照藝人統計每位藝人每天所有歌曲的播放量,輸出檔案為exp2_3.csv,各列名為藝人id,日期Ds,歌曲播放總量。注意:這裡只統計歌曲的播放量,不包括下載和收藏的數量。
解題想法:(利用pandas函式庫)
1.
(1)利用.drop_duplicates() 刪除重複值
#(2)利用.loc[:,‘artist_id’].value_counts() 求歌手重複次數,即每個歌手的歌曲數目
(3)利用.loc[:,‘ songs_id’].value_counts() 求出歌曲沒有重複
import pandas as pd data = pd.read_csv(r"C:\mars_tianchi_songs.csv") # 读取数据 Newdata = data.drop_duplicates(subset=['artist_id']) # 删除重复值 artist_sum = Newdata['artist_id'].count() #artistChongFu_count = data.duplicated(subset=['artist_id']).count() artistChongFu_count = data.loc[:,'artist_id'].value_counts() 重复次数,即每个歌手的歌曲数目 songChongFu_count = data.loc[:,'songs_id'].value_counts() # 没有重复(歌手) artistChongFu_count.loc['artist_sum'] = artist_sum # 没有重复(歌曲)artistChongFu_count.to_csv('exp2_1.csv') # 输出文件格式为exp2_1.csv
利用merge()合併兩個表
import pandas as pd import os data = pd.read_csv(r"C:\mars_tianchi_songs.csv") data_two = pd.read_csv(r"C:\mars_tianchi_user_actions.csv") num=pd.merge(data_two, data) num.to_csv('exp2_2.csv')
利用groupby()[].sum()進行重複性相加
import pandas as pd data =pd.read_csv('exp2_2.csv') DataCHongfu = data.groupby(['artist_id','Ds'])['gmt_create'].sum()#重复项相加DataCHongfu.to_csv('exp2_3.csv')
以上是如何使用Python操作文字資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

Dreamweaver CS6
視覺化網頁開發工具

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3漢化版
中文版,非常好用

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。