Home > Mobile >  Split string but returns separate words
Split string but returns separate words

Time:12-16

I was working on a project to identify partial matches of a string and a list.

The idea is to let python loop through a condition list and check whether the specified string contains any matches to the list.

FYI, the string I have is several filenames.

I tried to code as below:

import pandas as pd
import os
import re

from re import split

df = pd.read_excel(r"C:\Users\Asus\Desktop\py\con.xlsx")
id = df.iloc[:,3].tolist()
file_dir = "C:\Users\Asus\Desktop\Python\Input"

#read filenames and split filename
for x in os.listdir(file_dir):
    f_name = os.path.basename(x[:-4])
    print(f_name)
    for fname in f_name:
        new_fn = fname.split(r'_|-', 6) #here I wanted to set max 6 split
        print(new_fn)

#set conditions loop, rename file
if any(ele in new_fn for ele in id):
  print("Success")
  #here I also wish to rename the file
else:
  print("Fail")

FYI, the string (file name) is like CS123-5_3 (1)

After run the code, the output is like below

CS123-5_3 (1)
['C']
['S']
['1']
['2']
['3']
['-']
['5']
['_']
['3']
['(']
['1']
[')']
Fail #here fail refers to the if any statement

But my expected output should be like below

['CS123', '-', '5', '_', '3', '(1)']

Anyone can advice how I should improvise this code?

CodePudding user response:

Have you try using regex? enter image description here

  • Related