瞄准由垂直线分隔的单词 Python

发布于 2025-01-13 08:02:15 字数 912 浏览 3 评论 0原文

我有一个文本文件,其中存在此​​行。

 NAME                     = DE: NAME_DE |EN: NAME EN (EXAMPLE) |IT: NAME, IT

我想通过形成一个列表来定位三种语言的名称。 这是我的方法,但不幸的是,我找不到一种方法来仅定位三个单词:

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()

通过这种方式,我可以获得每个单词的列表,但我不能仅定位名称。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

林空鹿饮溪 2025-01-20 08:02:15

使用正则表达式,您可以通过搜索 :| 之间的子字符串来在一行中完成此操作。

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)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文