如何将 .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 文件中显示的列表成为我的 Processing 应用程序中的列表。

我试过使用 .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。 对于上下文(如有必要): 我的最终目标是从列表 "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() 从输入中定位 [] 可能会减少编码。

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

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

这样,您就可以得到 for 循环中每一行的列表。或者,您可以这样做:

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

通过这一行,您可以获得文件中 "" 之间所有内容的列表。

使用替换:

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

由于您正在加载的文件中包含实际的 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)

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

import re

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

print(ignored)

像这样的文本解析任务最好使用正则表达式。它是解析文本的最佳工具。在 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中的内置模块,所以不需要安装任何第三方库。有关正则表达式的更多信息,请参阅 here.

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

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