使用以下代码:
for root, dirs, files in os.walk(corpus_name):
for file in files:
if file.endswith(".v4_gold_conll"):
f= open(file)
lines = f.readlines()
tokens = [line.split()[3] for line in lines if line.strip()
and not line.startswith("#")]
print(tokens)
我收到以下错误:
Traceback (most recent call last): File "text_statistics.py", line 28, in corpus_reading_pos(corpus_name, option) File "text_statistics.py", line 13, in corpus_reading_pos f= open(file) FileNotFoundError: [Errno 2] No such file or directory: 'abc_0001.v4_gold_conll'
正如您所看到的,该文件实际上已找到,但是当我尝试打开该文件时,它...找不到它?
编辑: 使用此更新的代码,它在读取 7 个文件后停止,但有 172 个文件。
def corpus_reading_token_count(corpus_name, option="token"):
for root, dirs, files in os.walk(corpus_name):
tokens = []
file_count = 0
for file in files:
if file.endswith(".v4_gold_conll"):
with open((os.path.join(root, file))) as f:
tokens += [line.split()[3] for line in f if line.strip() and not line.startswith("#")]
file_count += 1
print(tokens)
print("File count:", file_count)
最佳答案
file
只是不带目录的文件,即代码中的 root
。试试这个:
f = open(os.path.join(root, file)))
此外,您最好使用 with
打开文件,而不是使用 file
作为变量名,从而遮蔽内置类型。另外,从您的评论来看,您可能应该扩展标记列表(使用 +=
而不是 =
):
tokens = []
for root, dirs, files in os.walk(corpus_name):
for filename in files:
if filename.endswith(".v4_gold_conll"):
with open(os.path.join(root, filename))) as f:
tokens += [line.split()[3] for line in f if line.strip() and not line.startswith("#")]
print(tokens)
关于python - 即使找到文件,也出现文件未找到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47941740/