![]() |
|
[Python] Hey guys I got a question about dictionaries! - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118) +---- Thread: [Python] Hey guys I got a question about dictionaries! (/showthread.php?tid=5581427) |
Hey guys I got a question about dictionaries! - twistingtide - Mar 21, 2017 So here is my situation 1. I am given a file with multiple paragraphs of random text. 2. A new paragraph is specified by a empty line or \n of course 3. I need to read through the file and separate each paragraph from each other, and I would like to make a dictionary 4. So I want the key in my dictionary to be the paragraph number 5. Then the value to be a list of each line in that paragraph. example of output below (by the way '#'s' are comments so I can help explain what I want) #File 1: #paragraph 1 'hey my name is joe' 'I am from the US' 'I love to play sports' \n \n #paragraph 2 'what do you like to do?' 'where are you from' \n \n So that is the text file example This is kind of what I want to do: d = {} d ={paragraph1 : [['hey my name is joe'], ['I am from the US'], ['I love to play sports']], paragraph2 : [['what do you like to do?'],['where are you from']]} But since I wont know how many paragraphs are in the file, nor will I know how many lines are in the paragraph, how can I read the file create a standard key value such as paragraph and every time a new paragraph appears increment it by one....I imagine you will use a loop to do this. * - hunter24957 - Mar 22, 2017 Here you go! PHP Code Output: Code {'paragraph 1': ['test', 'this'], 'paragraph 2': ['enjoy', 'this']}* - Goodies - Mar 22, 2017 @Hunter I doubt he wants each word in a list tbh. Definitely on the right track using a simple dict comprehension with enumerate, though. Just don't use paragraph.split() in that fashion. * - hunter24957 - Mar 22, 2017 (Mar 22, 2017 09:11 AM)Goodies Wrote: @Hunter I doubt he wants each word in a list tbh. Definitely on the right track using a simple dict comprehension with enumerate, though. Just don't use paragraph.split() in that fashion. Sorry, my example was a bit off. Picture the text file like this: Quote:test I shouldn't have used words instead of sentences, my bad. For a text file like this: Quote:hello my name is Jimmy this would be the output: Quote:{'paragraph 1': ['hello my name is Jimmy', 'Nice to meet you'], 'paragraph 2': ['How are you today?', 'I'm good thank you']}Just like he displayed as his preferred output. Well, he wanted the output like this: Quote:{paragraph1 : [['hey my name is joe'], ['I am from the US'], ['I love to play sports']], paragraph2 : [['what do you like to do?'],['where are you from']]}But then the embedded lists would be redundant due to them only containing one string each. |