0

I have a file like this and each line contains something like this string:

[{u'text': u'this', u'freq': 1}, {u'text': u'is', u'freq': 1}, {u'text': u'a', u'freq': 1}, {u'text': u'test', u'freq': 1}]

I tried to load each line into json object but I get this error:

for lineid, line in enumerate(open("myfile.txt")):
    jsonline=json.loads(line)

I get the following error:

raise ValueError(errmsg("Expecting property name", s, end))
ValueError: Expecting property name: line 1 column 2 (char 2)

I want to retrieve all 'text' from the file and have it in each line. So each line will not be json but will be the sequence of text space separated. Example:

this is a test

3
  • Is each line an item in a larger list? Commented Sep 17, 2015 at 1:52
  • each line is a line in a large file. Commented Sep 17, 2015 at 20:19
  • @Nick I noticed that you have never accepted any answer for your questions. I you don't want to, that is completely fine and you can ignore this comment. Just reminding you of the feature in case you forgot. Commented Dec 29, 2015 at 11:38

1 Answer 1

2

That's not JSON, that's a Python literal.

>>> import ast
>>> ast.literal_eval("[{u'text': u'this', u'freq': 1}, {u'text': u'is', u'freq': 1}, {u'text': u'a', u'freq': 1}, {u'text': u'test', u'freq': 1}]")
[{u'text': u'this', u'freq': 1}, {u'text': u'is', u'freq': 1}, {u'text': u'a', u'freq': 1}, {u'text': u'test', u'freq': 1}]
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks. Does it change it to the json object? How can I then retrieve the "text" fields?
It becomes a Python object. You treat it as you would the corresponding Python object.
Thanks. What do you think is the best way of extracting the "text" items? regular expression or json or ...?
How about accessing them the same way you would any other Python dict?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.