当前位置:网站首页>语料库数据处理个案实例(读取多个文本文件、读取一个文件夹下面指定的多个文件、解码错误、读取多个子文件夹文本、多个文件批量改名)
语料库数据处理个案实例(读取多个文本文件、读取一个文件夹下面指定的多个文件、解码错误、读取多个子文件夹文本、多个文件批量改名)
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()
边栏推荐
- 2022年PMP项目管理考试敏捷知识点(1)
- Anaconda 中使用 You Get
- [从零开始学习FPGA编程-42]:视野篇 - 后摩尔时代”芯片设计的技术演进-1-现状
- RDD的执行原理
- Q & A on cloud development cloudbase hot issues of "Huage youyue phase I"
- Extend ado Net to realize object-oriented CRUD (.Net core/framework)
- MySQL case: analysis of full-text indexing
- C code writing specification
- bjdctf_ 2020_ babystack
- Virtual machine security disaster recovery construction
猜你喜欢

鸿蒙os开发三

Camera calibration (calibration purpose and principle)

How to connect the Bluetooth headset to the computer and how to connect the win10 computer to the Bluetooth headset

光照使用的简单总结

Only two lines are displayed, and the excess part is displayed with Ellipsis
![(cve-2020-11978) command injection vulnerability recurrence in airflow DAG [vulhub range]](/img/33/d601a6f92b1b73798dceb027263223.png)
(cve-2020-11978) command injection vulnerability recurrence in airflow DAG [vulhub range]
![[GUET-CTF2019]zips](/img/79/22ff5d4a3cdc3fa9e0957ccc9bad4b.png)
[GUET-CTF2019]zips

Combine with (& &) logic or (||), dynamic binding and ternary operation
![LeetCode 515 在每个数行中找最大值[BFS 二叉树] HERODING的LeetCode之路](/img/16/011ba3aef1315c39526daac7e3ec89.png)
LeetCode 515 在每个数行中找最大值[BFS 二叉树] HERODING的LeetCode之路

More than 60 million shovel excrement officials, can they hold a spring of domestic staple food?
随机推荐
duilib 显示内存图片
6000多万铲屎官,捧得出一个国产主粮的春天吗?
Global and Chinese market of digital fryer 2022-2028: Research Report on technology, participants, trends, market size and share
The describeregion interface of CVM is special and has two versions
A case of bouncing around the system firewall
与(&&)逻辑或(||),动态绑定结合三目运算
How to delete / select an input method on your computer
tuple(元组)备注
Continue to have a fever. Try the asynchronous operation of dart language. The efficiency is increased by 500%
MFC multithreaded semaphore csemaphore critical area and mutually exclusive events
[从零开始学习FPGA编程-41]:视野篇 - 摩尔时代与摩尔定律以及后摩尔时代的到来
Étalonnage de la caméra (objectif et principe d'étalonnage)
Tencent cloud security and privacy computing has passed the evaluation of the ICT Institute and obtained national recognition
随机数备注
Anaconda 中使用 You Get
[DDCTF2018](╯°□°)╯︵ ┻━┻
MSSQL high permission injection write horse to Chinese path
Experience of Shenzhou computer
Common coding and encryption in penetration testing
More than 60 million shovel excrement officials, can they hold a spring of domestic staple food?