Python 如何使用pathlib从多个文件路径中提取词干?

Python 如何使用pathlib从多个文件路径中提取词干?,python,pathlib,Python,Pathlib,我正在尝试使用pathlib从多个文件路径中提取stem,但失败了 以下是我尝试的代码: base_path = Path(__file__).parent paths = (base_path / "../dictionary/files/").glob('**/*') files = [x for x in paths if x.is_file()] for i in range(len(files)): stem_name = files.stem[i] 以下是错误: for

我正在尝试使用pathlib从多个文件路径中提取stem,但失败了

以下是我尝试的代码:

base_path = Path(__file__).parent
paths = (base_path / "../dictionary/files/").glob('**/*')
files = [x for x in paths if x.is_file()]
for i in range(len(files)):
     stem_name = files.stem[i]
以下是错误:

for i in range(len(files)):
TypeError: object of type 'generator' has no len()
我有名为1.txt、2.txt、3.txt的文本文件

预期:

1
2
3
你很接近

您应该为列表中的文件编制索引,然后列表文件[i]的每个元素都将是一个实例,它将使用.stem方法

但是我不确定这个错误,因为它不能从发布的代码中复制:

仅当您使用创建文件或使用文件=。。。而不是列表文件=[…]。在这两种情况下,你都会在发电机上给len打电话,但那是行不通的,因为

你很接近

您应该为列表中的文件编制索引,然后列表文件[i]的每个元素都将是一个实例,它将使用.stem方法

但是我不确定这个错误,因为它不能从发布的代码中复制:

仅当您使用创建文件或使用文件=。。。而不是列表文件=[…]。在这两种情况下,你都会在发电机上给len打电话,但那是行不通的,因为


@耶斯雷尔知道怎么做吗?@耶斯雷尔知道怎么做吗?
for file_ in files:
    stem = file_.stem
    print(stem)
for i in range(len(files)):
    stem_name = files[i].stem
(test-py38) gino:Q$ cat test.py
from pathlib import Path

base_path = Path(__file__).parent
paths = (base_path / "./files").glob('**/*')
files = [x for x in paths if x.is_file()]
for i in range(len(files)):
    stem_name = files[i].stem
    print(stem_name)

(test-py38) gino:Q$ ls files
1.txt  2.txt  3.txt

(test-py38) gino:Q$ python test.py
2
3
1
for i in range(len(files)):
    TypeError: object of type 'generator' has no len()
(test-py38) gino:Q$ cat test.py
from pathlib import Path

base_path = Path(__file__).parent
paths = (base_path / "./files").glob('**/*')
files = (x for x in paths if x.is_file())  # <---- generator expression
for i in range(len(files)):
    stem_name = files[i].stem
    print(stem_name)

(test-py38) gino:Q$ python test.py
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    for i in range(len(files)):
TypeError: object of type 'generator' has no len()
files = (x for x in paths if x.is_file())
for a_file in files:
    stem_name = a_file.stem