繁体   English   中英

如何将 .txt 文件中的列表转换为 Processing (python) 中的列表?

[英]How do I convert a list in a .txt file to a list in Processing (python)?

我的家庭作业遇到了问题。 在文本文件中,有以下内容:

ignored = ["the", "a", "an", "i", "me", "you", "with", "this"]

(实际内容要长得多,但为了简单起见,我缩短了它。)

我希望 .txt 文件中显示的列表成为我的处理应用程序中的列表。

我尝试使用 .strip 和 .split 使其工作:

size(500,500)
ignored = []
g = open("ignored.txt", "r")

for line in g:
    line = line.strip('ignored')
    line= line.strip()
    line = line.strip("=")
    line = line.strip()

    line = line.strip("][")

    line = line.split(", ")

    print(line)
    ignored.append(line)

ignored.pop()
print(ignored)

我尝试了 .strip 或 .split 的多种组合,但我的打印输出一直是这个或类似的东西。

[['"the"', '"a"', '"an"', '"i"', '"me"', '"you"', '"with"', '"this"']]

我希望我的最终列表缺少额外的引号和括号。 类似于:["the", "a", "an", "i", "me", "you", "with", "this"]

我无法找到一种方法来完成这项工作,我认为有一种更简单的方法。

我无法导入任何内容,并且我使用的是最新版本的 Processing。 对于上下文(如有必要):我的最终目标是从“忽略”列表中取出单词并从另一个列表中删除这些单词。

如果有的话,请告诉我您需要什么其他信息来帮助我。 谢谢你的时间。

您可以使用正则表达式( import re ):

my_list = re.findall(r'"(\w+)"', line)
ignored.append(my_list)

这样,您将获得for循环中每一行的列表。 或者,你可以这样:

ignored = re.findall(r'"(\w+)"', g.read())

使用这个简单的行,您可以获得文件中""之间的所有内容的列表。

由于您正在加载的文件中包含实际的 Python 代码,因此获取它的一种方法是复制或重命名它并导入它。 显然不是一般推荐的东西,如果事实上它有点麻烦,但任务似乎假设你在这种情况下会做类似的事情。

import shutil

shutil.copy('ignored.txt', 'ignored.py')
from ignored import ignored

print(ignored)

除了不安全之外,这还有一个缺点,就是告诉您它无法从检查这些内容的编辑器中找到被忽略的模块,就像大多数 IDE 一样。 另一个简单但也不是很安全的解决方案是将文件的内容作为 Python 进行评估而不导入它。

ignored = []

with open('ignored.txt', 'r') as f:
    content = f.read()
    exec(content)

print(ignored)

一个更安全且可以说是更好的解决方案是解析文件的内容并只选择您想要的元素。 但是,不是像您的示例那样手动执行此操作,而是可以使用正则表达式来获取您需要的内容 - 假设它只包含与您提供的类似的行:

import re

with open('ignored.txt', 'r') as f:
    content = f.read()
    ignored = [match.group(1) for match in re.finditer('[\'"](.*?)[\'"]', content)]

print(ignored)

请尝试以下操作:

ignored = []
g = open("text.txt", "r")

for line in g:
    start_index = line.find('[') + 1
    end_index = line.find(']')
    l = line[start_index:end_index]
    l = l.replace('"', '')
    l = l.split()
    ignored.extend(l)
print(ignored)

使用此代码应该相当简单:

import ast
with open("ignored.txt", "r") as f:
    f = f.read().strip("ignored = ")

    print(ast.literal_eval(f))

Out[0]: ['the', 'a', 'an', 'i', 'me', 'you', 'with', 'this']

请注意, with open()一起使用通常更好、更简洁,因为它会在您完成使用相关文件后自动关闭您的文件以释放任何浪费的内存。 否则,请确保在完成对文件的读取或写入后运行f.close()

看起来您只需要再次使用 strip 即可从文本文件中删除引号。

此外,在使用 split(",") 之前使用 find() 从输入中定位 [] 可能更少编码。

您最好将正则表达式用于像这样的文本解析任务。 它是解析文本的最佳工具。 在txt文件中提取列表的示例代码如下:

import re

with open('test.txt', 'rb') as f:
    line = f.readline()
    pattern = '"(.*?)"' # this means: any characters between double quotation marks
    ignored = re.findall(pattern , line) # this method returns a list of strings that match pattern

上面代码中的一些假设:

  • 您的 txt 文件名为 test.txt,它只有 1 行,该行包含列表。

  • 您的列表是一个字符串列表,每个字符串都包含在一对双引号内。

re是 Python 中的内置模块,因此无需安装任何第三方库。 可以在此处找到有关正则表达式的更多信息。

我能够通过以下方式做到这一点:

text1='''ignored = ["the", "a", "an", "i", "me", "you", "with", "this"]'''

list1=text1.split('[')[-1][:-1].replace('"','').split(',')
print(list1)
Out: ['the', ' a', ' an', ' i', ' me', ' you', ' with', ' this']

或者用这个

list1=text1.split('[')[-1].strip(']').replace('"','').split(',')

我只是硬编码了您的文本行,以便于测试。

忽略 = ["the", "a", "an", "i", "me", "you", "with", "this"]

with open("ignored.txt", "r") as f:
    for line in f:
        if line.startswith('ignored = ['):
            list = line.replace('ignored = [','').replace(']').replace('"', '').strip(',')
        print list

使用替换:

line.replace('"','').replace('[','') etc...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM