当前位置:网站首页>语料库数据处理个案实例(读取多个文本文件、读取一个文件夹下面指定的多个文件、解码错误、读取多个子文件夹文本、多个文件批量改名)
语料库数据处理个案实例(读取多个文本文件、读取一个文件夹下面指定的多个文件、解码错误、读取多个子文件夹文本、多个文件批量改名)
2022-06-24 06:46:00 【Triumph19】
7.10 读取多个文本文件
- 在前面的章节中,我们示范了如何读取单个文本文件,并对之进行相关文本处理。在语料库语言学研究中,语料库往往存储在多个文本中。本小节中,我们首先介绍如何读取文件夹中多个文本的文件名;然后介绍如何读取多个文件,并将它们合并成一个文本;最后介绍如何读取多个子文件夹中的文本。
7.10.1 读取文件夹中多个文件的文件名
- 本小节中我们提供示例:如何读取某文件夹中多个文件的文件名。我们需要完成的任务是打印D:\works\文本分析\leopythonbookdata-master\texts文件夹所有txt文本文件。请看下面的代码。
import os
target_dir = r'D:\works\文本分析\leopythonbookdata-master\texts'
files = os.listdir(target_dir)
for file in files:
if file.endswith(r'.txt'):
print(file)

- 首先通过import os 语句引入 os 库,然后,定义需要读取的目标文件夹路径和文件名。接下来,通过os.listdir()函数来读入文件夹中的所有文件名。
- os.listdir()函数需要一个参数,是需要读取的文件夹的路径和文件夹名。它将读取的文件夹中的所有文件名保存为一个列表,列表的每一个元素为一个文件名。下面的for … in 循环遍历读取的文件名,如果文件名以“.txt”结尾,则打印该文件名。
7.10.2 合并多个文本(解码错误的解决办法)
- 本小节我们读取D:\works\文本分析\leopythonbookdata-master\texts文件夹中所有的txt文本文件,并将这些文本文件的内容合并到一个新建的文本文件"filles_combined.txt"中,请看下面的代码。
import os
target_dir = 'D:/works/文本分析/leopythonbookdata-master/texts/'
files = os.listdir(target_dir)
file_out = open(target_dir + 'files_combined.txt','a',encoding='utf8')
for file in files:
if file.endswith(r'.txt'):
file_in = open(target_dir + file,'r',encoding='ISO-8859-1')#这里没有encoding,亦或用'utf8'编码都会出现报错
text = file_in.readlines()
for t in text:
file_out.write(t)
file_in.close()
file_out.close()
- 关于解码错误问题的解决方法,参考:Python——报错 UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xce in position 52: invalid continuation byte问题解决
7.10.3 读取多个子文件夹文本
- 前面两个小节我们介绍了如何利用os.listdir()函数读取一个文件夹中的多个文本。但是,如果文件夹中含有子文件夹,os.listdir()函数并不能读取子文件夹中的文本。在语料库研究中,文本往往可能存储在一个文件夹下的多个子文件夹中,如果要读取子文件夹中的文本,就需要使用os模块的os.walk()函数。
- 我们来看下面的例子。假设语料库为D:/works/文本分析/leopythonbookdata-master/texts/文件夹中的所有以.txt结尾的文本文件。该文件夹中又有D:/works/文本分析/leopythonbookdata-master/texts/temp_folder/子文件夹,该子文件夹中也有数个文本文件。下面的代码展示如何读取D:/works/文本分析/leopythonbookdata-master/texts/文件夹(包括子文件)中的所有文本文件。
import os
rootdir = 'D:/works/文本分析/leopythonbookdata-master/texts/'
allfiles = []
for root,subFolder,files in os.walk(rootdir):
for file in files:
allfiles.append(os.path.join(root,file))
for i in allfiles:
if i.endswith('.txt'):
print(i)
- 上面代码的第一二行,我们首先通过import os 引入os模块,然后定义语料库所有的文件夹(rootdir = ‘D:/works/文本分析/leopythonbookdata-master/texts/’)。第三行,我们定义一个空列表allfiles,用以储存所有带有绝对路径的文件名。第四行,我们循环遍历rootdir文件夹中的根目录(root)、子目录(subFolders)和根目录下所有带有绝对路径的文件名(files)。其中,最重要的是files,它是一个列表,包含所有根目录下(含子文件夹)带有绝对路径的文件名。读者可以在该循环中加如下三行代码,打印出root,subFolders,files的内容,以更深入了解它们的内容。代码如下:
for root,subFolder,files in os.walk(rootdir):
# print('root:',root)
# print('subFolders:',subFolder)
# print('files:',files,'\n')
- 我们可以将上面的代码进行修改,读取每个文件,并将它们合并到一个文本中。请看下面的代码。
import os
rootdir = 'D:/works/文本分析/leopythonbookdata-master/texts/'
allfiles = []
file_out = open(rootdir + 'allfiles_combined.txt','a',encoding='utf8')
for root,subFolder,files in os.walk(rootdir):
for file in files:
allfiles.append(os.path.join(root,file))
for i in allfiles:
if i.endswith('.txt'):
file_in = open(i,'r',encoding='ISO-8859-1')
for line in file_in.readlines():
file_out.write(line)
file_in.close()
file_out.close()
7.11 多个文件批量改名
- 本小节我们读取’D:/works/文本分析/leopythonbookdata-master/texts/temp_folder/‘文件夹中的所有文本文件,并将每个文本的文件名改名为’源文件主题部分_changed.txt’。请看下面的代码。
import os
target_dir = 'D:/works/文本分析/leopythonbookdata-master/texts/temp_folder/'
files = os.listdir(target_dir)
for file in files:
if file.endswith(".txt"):
# open the txt file
file_in = open(target_dir + file,'r',encoding='ISO-8859-1')
text = file_in.readlines()
# open the new txt file with file name changed
file_out = open(target_dir + file[:-4] + "_changed.txt",'a')
for t in text:
file_out.write(t)
file_in.close()
file_out.close()
边栏推荐
猜你喜欢

Shader 常用函数

Étalonnage de la caméra (objectif et principe d'étalonnage)
![[vulhub shooting range]] ZABBIX SQL injection (cve-2016-10134) vulnerability recurrence](/img/c5/f548223666d7379a7d4aaed2953587.png)
[vulhub shooting range]] ZABBIX SQL injection (cve-2016-10134) vulnerability recurrence

Combine with (& &) logic or (||), dynamic binding and ternary operation

图形技术之坐标转换

Win10 build webservice

RDD basic knowledge points

屏幕截图推荐—Snipaste

Win11 points how to divide disks? How to divide disks in win11 system?
![LeetCode 515 在每个数行中找最大值[BFS 二叉树] HERODING的LeetCode之路](/img/16/011ba3aef1315c39526daac7e3ec89.png)
LeetCode 515 在每个数行中找最大值[BFS 二叉树] HERODING的LeetCode之路
随机推荐
与(&&)逻辑或(||),动态绑定结合三目运算
图形技术之管线概念
洛谷 P1051 谁拿了最多奖学金
常见的数组封装
Combine with (& &) logic or (||), dynamic binding and ternary operation
The seminar on "global IPv6 development and outlook 2020-2021" was held in Beijing
pair类备注
[DDCTF2018](╯°□°)╯︵ ┻━┻
[frame rate doubling] development and implementation of FPGA based video frame rate doubling system Verilog
Maxcompute remote connection, uploading and downloading data files
Mysql database recovery case sharing
Accessing user interface settings using systemparametersinfo
Hubei College Upgraded to undergraduate - Hushi family planning department
Exploration on Optimization of elastic expansion engineering
MFC multithreaded semaphore csemaphore critical area and mutually exclusive events
tuple(元组)备注
Actual target shooting - skillfully use SMB to take down the off-line host
[mrctf2020] thousand layer routine
[wustctf2020] climb
Unity 的序列化