python - 从python中的文件名中检索单词

标签 python string pandas filenames series

我在特定路径中有 5 个 Excel 文件的列表,如下所述:'Z:\\Ruchika\\Citymax_Dec06\\SVCDs\\**\\*Claypot*.csv'。 5个excel文件的列表和路径如下

['Z:\\Ruchika\\Citymax_Dec06\\SVCDs\\December - SVCD\\UAE _ Citymax _Claypot_ Burdubai_fullcampaignfile.csv',
 'Z:\\Ruchika\\Citymax_Dec06\\SVCDs\\January2019 - SVCD\\UAE _ Citymax _Claypot_ Burdubai_fullcampaignfile.csv',
 'Z:\\Ruchika\\Citymax_Dec06\\SVCDs\\November - SVCD\\UAE _ Citymax _ Claypot_BD_fullcampaignfile.csv',
 'Z:\\Ruchika\\Citymax_Dec06\\SVCDs\\October - SVCD\\UAE _ Citymax _Claypot_ Burdubai_fullcampaignfile.csv',
 'Z:\\Ruchika\\Citymax_Dec06\\SVCDs\\sept - svcd\\UAE _ Claypot _ Burdubai_fullcampaignfile.csv']

现在,我尝试从每个 Excel 文件名中检索月份名称,并按照下面的代码添加到我的数据框中,但由于我只能检索 11 月份的月份名称而受到打击,这是不正确的。请帮助我

m=['November','December','October','September','August']
    def extract(folderpath):
        final=glob.glob(folderpath)
        frames = []
        for file in final:
            j=0
            df = pd.read_csv(file, error_bad_lines=False)
            df['Month']=m[j]
            frames.append(df)
            j=j+1
        mergedfile = pd.concat(frames)
        return mergedfile

a=extract('Z:\\Ruchika\\Citymax_Dec06\\SVCDs\\**\\*Claypot*.csv')

Input : a.shape
Ouput : (3232487, 31)

Input : a['Month'].value_counts()
Output : November   3232487
         Name: Month, dtype: int64

最佳答案

我猜它可以是任何月份,所以为什么不只检查月份:

filename = r'Z:\Ruchika\Citymax_Dec06\SVCDs\December - SVCD\UAE _ Citymax Claypot Burdubai_fullcampaignfile.csv'

for month in ['October', 'November', 'December']: # List of months
    if month in filename:
        print('Month is:', month)

关于python - 从python中的文件名中检索单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54092650/

相关文章:

python - 运行 dict.clear 但字典仍然打印项目

java - 我有两个非常相似的 C 函数被 python 和 Java 调用。如何将 2 个库合并为 1 个可以从两种语言调用的库?

c# - 子串索引许多相似的字符串

C - 函数未在输入字符串末尾终止导致段错误

python - 访问 Pandas 中的最后 X 行应用

python - OpenCV Python 计数像素

python - 从列表中读入MySql

c - 在链表c中插入字符串

python - 如何对具有混合数据类型的 pandas 数据框中的浮点(十进制)值进行舍入?

python - 将数据帧转换为 numpy 数组时如何保持数据类型?