Python 遍历目录并打开一个 txt 文件
Python walk through directory and open a txt file
我正在尝试使用 saprql 查询打开和处理我从维基百科下载的数千个文本文件。我使用以下代码:
list_words=[]
for roots, dirs, files in os.walk(path):
for file in files:
if file.endswith(".txt"):
with open(file, 'r') as f:
content= f.read()
#remove the punct
table=string.maketrans(string.punctuation,' '*len(string.punctuation))
s= content.translate(table)
#remove the stopwords
text= ' '.join([word for word in s.split() if word not in stopwords])
alfa= " ".join(text.split())
#remove the verbs
for word, pos in tag(alfa): # trovo tutti i verbi.
if pos != "VB":
lower= word.lower()
lower_2= unicode(lower, 'utf-8', errors='ignore')
list_words.append(lower_2)
#remove numbers
testo_2 = [item for item in list_words if not item.isdigit()]
print set(list_words)
问题是脚本打开了一些文本文件,而对于其他文件,它给我错误:"Not such file or directory: blablabla.txt"
有人知道为什么会这样吗?我该如何应对?
谢谢!
file
是相对的,你必须像这样连接根和文件以获得绝对文件名:
absolute_filename = os.path.join(roots, file)
with open(absolute_filename, 'r') as f:
.... rest of code
(应该命名为 root
而不是 roots
)。
我正在尝试使用 saprql 查询打开和处理我从维基百科下载的数千个文本文件。我使用以下代码:
list_words=[]
for roots, dirs, files in os.walk(path):
for file in files:
if file.endswith(".txt"):
with open(file, 'r') as f:
content= f.read()
#remove the punct
table=string.maketrans(string.punctuation,' '*len(string.punctuation))
s= content.translate(table)
#remove the stopwords
text= ' '.join([word for word in s.split() if word not in stopwords])
alfa= " ".join(text.split())
#remove the verbs
for word, pos in tag(alfa): # trovo tutti i verbi.
if pos != "VB":
lower= word.lower()
lower_2= unicode(lower, 'utf-8', errors='ignore')
list_words.append(lower_2)
#remove numbers
testo_2 = [item for item in list_words if not item.isdigit()]
print set(list_words)
问题是脚本打开了一些文本文件,而对于其他文件,它给我错误:"Not such file or directory: blablabla.txt"
有人知道为什么会这样吗?我该如何应对?
谢谢!
file
是相对的,你必须像这样连接根和文件以获得绝对文件名:
absolute_filename = os.path.join(roots, file)
with open(absolute_filename, 'r') as f:
.... rest of code
(应该命名为 root
而不是 roots
)。