I have a text file in which this line is present.
NAME = DE: NAME_DE |EN: NAME EN (EXAMPLE) |IT: NAME, IT
I would like to target the names in the three languages by forming a list. This is my approach, but unfortunately I cannot find a way to target just the three words:
materialfile_obj = open (material_dict["Old_plaster"], 'r',encoding = 'latin-1')
materialfile = materialfile_obj.readlines()
flag_name = 0
for i in range(len(materialfile)):
if "NAME" in materialfile[i] and "=" in materialfile[i]:
line_name = i
flag_name = 1
if flag_name == 1:
names = materialfile[line_name].split(" = ")[1].split()
if names:
for name in names:
try:
Name_groups[name].append(All)
except Exception:
Name_groups[name] = [All]
else:
try:
Name_groups["No_value"].append(All)
except Exception:
Name_groups["No_value"] = [All]
materialfile_obj.close()
in this way I get a list for each word present but I cannot target only the names.
CodePudding user response:
With regular expressions you can do it on one line by searching for substrings between : and |.
import re
s = 'NAME = DE: NAME_DE |EN: NAME EN (EXAMPLE) |IT: NAME, IT'
s = '|' # add pipe to find strings between : and |
names = re.findall(':(.*?)[|]', s)
print(names)