I'm running into an issue with my homework assignment. In a text file, there is the following:
ignored = ["the", "a", "an", "i", "me", "you", "with", "this"]
(the actual contents are much longer, but I shortened it for simplicity.)
I want the list shown in the .txt file to become a list in my Processing app.
I've tried using .strip and .split to make it work:
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)
I've tried many combinations of what to .strip or .split, but my output from print has always been this or something similar.
[['"the"', '"a"', '"an"', '"i"', '"me"', '"you"', '"with"', '"this"']]
I would like my final list to be missing the extra quotes and brackets. Something like: ["the", "a", "an", "i", "me", "you", "with", "this"]
I cannot finagle a way to make this work, and I'm thinking there is an easier way.
I cannot import anything, and I'm using the latest version of Processing. For context (if necessary): My ultimate goal is to take the words from the list "ignored" and remove those words from another list.
Let me know what, if any, other info you need to help me out. Thanks for your time.
Since the file you're loading has actual Python code in it, one way to get it would be to copy or rename it and just import it. Obviously not something that's generally recommended, if fact it's a bit of a bodge, but the assignment seems to assume you'd do something like it in this case.
import shutil
shutil.copy('ignored.txt', 'ignored.py')
from ignored import ignored
print(ignored)
Apart from being unsafe, this has the downside of telling you it can't find the ignored module from editors that check these things, like most IDEs will. Another simple solution, but also not very safe, is to evaluate the contents of the file as Python without importing it.
ignored = []
with open('ignored.txt', 'r') as f:
content = f.read()
exec(content)
print(ignored)
A safer and arguably better solution would be to parse the contents of the file and only select the elements you're after. But instead of doing that manually, like your example, you could use a regular expression to get the content you need - assuming it only contains a line like the one you provided:
import re
with open('ignored.txt', 'r') as f:
content = f.read()
ignored = [match.group(1) for match in re.finditer('[\'"](.*?)[\'"]', content)]
print(ignored)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments