【问题标题】:return a list of word from a texte file with python使用python从文本文件中返回单词列表
【发布时间】:2021-09-01 13:08:07
【问题描述】:

我在 python 上做一个项目。 我想从文本文件中返回名称列表。 我从一个我知道的名字开始。 我的文本文件是这样的:

ALPHA;n10;Output 
ALPHA;n11;Input 
ALPHA;n12;Input 
BETA;n10;Input 
BETA;n14;Input 
CHARLIE;n10;Input 
CHARLIE;n13;Output 
DELTA;n13;Output 
DELTA;n12;Input

假设我从名称 ALPHA 开始,我知道它是一个输出。 所以我必须搜索这个名字的号码链接,即 n10。 我想返回输入中数字 n10 的所有名称。 所以最后我想要列表 ["BETA", "CHARLIE"]

目前我编写了以下函数:

file = "path of the texte file"
name = "ALPHA"
liste_new_name = []
def search_new_name(liste):
    file_txt = open(file, "r")
    contenu = file_txt.readline()
    file_txt.close()
    if contenu.split(";")[0] == name and ";Output" in contenu:
        num = contenu.split(";")[1]
        if num in contenu and ";Input" in contenu:
             liste.append(contenu.split(";")[0]
             return liste
             print(liste)
        else:
             print("No new name found")
    else:
        print("No num found")

search_new_name(liste_new_name)

我的问题是我“找不到编号”,但就像我知道的示例一样,我应该有一个列表。

【问题讨论】:

  • return liste 立即退出函数。
  • 在搜索完整个文件之前不要print("No num found")
  • 您应该阅读文件中的所有行并遍历它们,检查每一行。您也可以考虑使用 CSV 解析器。
  • 兄弟检查contenu值兄弟你会得到答案
  • file_txt = open(file, "r") contenu = file_txt.readline() file_txt.close() 只读取文件的第一行

标签: python list text-files


【解决方案1】:

我会将文件解析成字典。这将使搜索变得更加容易,并且允许您进行多次搜索而无需重新读取文件:

def parse_file(path):
    data = {}
    with open(path, 'r') as in_file:
        for line in in_file:
            try:
                name, n, direction = line.strip().split(';')
                if name not in data:
                    data[name] = {"Input": [], "Output": []}
                data[name][direction].append(n)
            except KeyError:
                print(f"Error with: {line}")
            except ValueError:
                pass
    return data

这将返回一个像这样的字典:

{
'ALPHA': {'Input': ['n11', 'n12'], 'Output': ['n10']},
'BETA': {'Input': ['n10', 'n14'], 'Output': []},
'CHARLIE': {'Input': ['n10'], 'Output': ['n13']},
'DELTA': {'Input': ['n12'], 'Output': ['n13']}
}

这样搜索就可以通过简单的列表理解来完成:

def search_new_name(name, data):
    if name not in data: return None
    return [key for key,value in data.items() if any(x in data[key]["Input"] for x in data[name]["Output"])]

示例用法:

data = parse_file(r"C:\foo\bar.txt")
print(search_new_name("ALPHA", data))

输出:

['BETA', 'CHARLIE']

【讨论】:

  • 感谢您的想法。但是,当我用我的案例执行代码时,我有一个“KeyError:'SK'”。它表示data[name][direction].append(n) 行中有错误。
  • @Alex 导致错误的行不能有“输入”和/或“输出”。您可以为此添加支票。我会更新答案。
【解决方案2】:

您将必须阅读所有行并使用“数字”和“类型”组合创建字典作为解决问题的关键。

file = "path of the texte file"
name = "ALPHA"
liste_new_name = []

def search_new_name(name):
    name_map = {} ## dict to save all the info
    search_key = False
    file_txt = open(file, "r")
    all_lines = file_txt.readlines()
    for contenu in all_lines:
        [l_name,l_num,l_type] = contenu.split(";")
        key = l_num + "_" + l_type ## use num and type combination as a key
        if l_name == name and l_type == "Output":
            search_key = l_num+"_"+l_type
        if key in name_map:
            name_map[key] = name_map[key].append(l_name)
        else:
            name_map[key] = [l_name]

    if search_key is False:
        print("Num not found")
        return []
    else:
        search_num = search_key.split('_')[0]
        if search_num+'_Input' in name_map:
            return name_map[search_num+'_Input']
        else:
            ## return empty list if no input found
            return []


search_new_name(name)

【讨论】:

  • 感谢您的想法。我对@Johnny Mopp 也有类似的错误。错误参考以下行name_map[key] = name_map[key].append(l_name)
  • 据说 AttributeError: 'NoneType' object has no attribute 'append'
  • 是的,我的错! - 只需制作name_map[key].append(l_name),它应该可以工作
【解决方案3】:

我尝试用两个这样的功能继续我的想法:

file = "path of the text file"
name = "ALPHA"
new_l_name = []
num = []

def search_num(num):
    file_txt = open(file, "r")
    contenu = file_txt.readline()
    while contenu:
        contenu = fichier_txt.readline()
        if contenu.split(";")[0] == name and ";Output" in contenu:
            num.append(contenu.split(";")[1]
            return num
    else:
        print("No num found")
    file_txt.close()

search_num(num)

def search_new_name(liste):
    file_txt = open(file, "r")
    contenu = file_txt.readline()
    while contenu:
        contenu = file_txt.readline()
        if contenu.split(";")[1] == num[0] and ";Input" in contenu:
            new_name = contenu.split(";")[0]
            liste.append(new_name)
            print("the list of new name : {}".format(liste))
            return liste
    else:
        print("No new name found")

search_new_name(new_l_name)
    

最后,我得到了我们搜索的 num,但新名称的列表返回了在文本文件中找到的第一个新名称的列表,而不是其他名称。它返回 ["BETA"] 而不是我们想要的 ["BETA", "CHARLIE"]。

如果有人有想法。

谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多