Splitting A List At Certain Characer - python

say I have a list that goes something like this:
['Try not to become a man of success, but rather try to become a man of value.
\n', 'Look deep into nature, and then you will understand everything
better.\n', 'The true sign of intelligence is not knowledge but imagination.
\n', 'We cannot solve our problems with the same thinking we used when we
created them. \n', 'Weakness of attitude becomes weakness of character.\n',
"You can't blame gravity for falling in love. \n", 'The difference between
stupidity and genius is that genius has its limits. \n']
How would I go about splitting this list into sub-lists at every newline?
How do I turn the output above to my desired output below?
['Try not to become a man of success, but rather try to become a man of value.']
['Look deep into nature, and then you will understand everything better'] ['The true sign of intelligence is not knowledge but imagination.]

Your expected result seems like a list of item where each item is a list containing a single element composed of the list item stripped of whitespaces, something that can be achieved using:
result = [[line.strip()] for line in lines]

Related

string.punctuation fails to remove certain characters from a string

My aim is to remove all punctuations from a string so that I can then get the frequency of each word in the string.
My string is:
WASHINGTON—Coming to the realization in front of millions of viewers
during the broadcast of his show, a horrified Tucker Carlson stated,
‘I…I am the mainstream media’ Wednesday as he began spiraling live on
air. “We’ve discovered evidence of rampant voter fraud, and the
president has every right to call for an investigation even if the
mainstream media thinks...” said Carlson, who trailed off, stared down
at his shaking hands, and felt a sudden ringing in his ears as he
looked back up and zeroed in on the production crew surrounding him.
“The media says…wait. Those liars on TV will try to tell you…oh God.
We’re the number-one program on cable news, aren’t we? Fox News…Fox
‘News.’ It’s the media. It’s me. This can’t be. No, no, no, no. Jesus
Christ, I make $6 million a year. Get that camera off me!” At press
time, Carlson had torn the microphone from his lapel and fled the set
in panic.
source: https://www.theonion.com/i-i-am-the-mainstream-media-realizes-horrified-tuc-1845646901
I want to remove all punctuations from it. I do that like this -
s.translate(str.maketrans('', '', string.punctuation))
This is the output -
WASHINGTON—Coming to the realization in front of millions of viewers
during the broadcast of his show a horrified Tucker Carlson stated
‘I…I am the mainstream media’ Wednesday as he began spiraling live on
air “We’ve discovered evidence of rampant voter fraud and the
president has every right to call for an investigation even if the
mainstream media thinks” said Carlson who trailed off stared down at
his shaking hands and felt a sudden ringing in his ears as he looked
back up and zeroed in on the production crew surrounding him “The
media says…wait Those liars on TV will try to tell you…oh God We’re
the numberone program on cable news aren’t we Fox News…Fox ‘News’ It’s
the media It’s me This can’t be No no no no Jesus Christ I make 6
million a year Get that camera off me” At press time Carlson had torn
the microphone from his lapel and fled the set in panic
As you can see that characters/ string like ", — and ... still exist. Am I incorrectly expecting them to be removed too? If the output is correct then how can I NOT differentiate between "`News`" and "News"?
>>> import string
>>> "“" in string.punctuation
False
>>> "—" in string.punctuation
False
Welcome to the wonderful world of Unicode where, among many other things, … is not three concatenated full stop periods and :
>>> import unicodedata
>>> unicodedata.name('—')
'EM DASH'
is not a hyphen.
How you want to handle the full scope of what could be considered 'punctuation' across the Unicode table is probably out of scope for this question, but you could either come up with your own ad-hoc list or use a third-party library designed for that type of text manipulation. Here is one such approach:
Best way to strip punctuation from a string
I added the list of characters you can remove from string by using your implementation.
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?#[\\]^_`{|}~'
You can check this implementation to remove all special characters and keep whitespaces
''.join(e for e in s if e.isalnum() or e == ' ')
It looks like the … and a couple of the other characters you are having trouble with are special Unicode characters. A workaround is to use string.isalpha(), which tells you whether the characters of a string are part of the alphabet or not.
result = ""
for x in string:
if x.isalpha() or x == " ":
result = result + x

Splitting text into sentences using regex in Python [duplicate]

This question already has answers here:
How can I split a text into sentences?
(20 answers)
Closed 3 years ago.
I'm trying to split a piece sample text into a list of sentences without delimiters and no spaces at the end of each sentence.
Sample text:
The first time you see The Second Renaissance it may look boring. Look at it at least twice and definitely watch part 2. It will change your view of the matrix. Are the human people the ones who started the war? Is AI a bad thing?
Into this (desired output):
['The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing']
My code is currently:
def sent_tokenize(text):
sentences = re.split(r"[.!?]", text)
sentences = [sent.strip(" ") for sent in sentences]
return sentences
However this outputs (current output):
['The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing', '']
Notice the extra '' on the end.
Any ideas on how to remove the extra '' at the end of my current output?
nltk's sent_tokenize
If you're in the business of NLP, I'd strongly recommend sent_tokenize from the nltk package.
>>> from nltk.tokenize import sent_tokenize
>>> sent_tokenize(text)
[
'The first time you see The Second Renaissance it may look boring.',
'Look at it at least twice and definitely watch part 2.',
'It will change your view of the matrix.',
'Are the human people the ones who started the war?',
'Is AI a bad thing?'
]
It's a lot more robust than regex, and provides a lot of options to get the job done. More info can be found at the official documentation.
If you are picky about the trailing delimiters, you can use nltk.tokenize.RegexpTokenizer with a slightly different pattern:
>>> from nltk.tokenize import RegexpTokenizer
>>> tokenizer = RegexpTokenizer(r'[^.?!]+')
>>> list(map(str.strip, tokenizer.tokenize(text)))
[
'The first time you see The Second Renaissance it may look boring',
'Look at it at least twice and definitely watch part 2',
'It will change your view of the matrix',
'Are the human people the ones who started the war',
'Is AI a bad thing'
]
Regex-based re.split
If you must use regex, then you'll need to modify your pattern by adding a negative lookahead -
>>> list(map(str.strip, re.split(r"[.!?](?!$)", text)))
[
'The first time you see The Second Renaissance it may look boring',
'Look at it at least twice and definitely watch part 2',
'It will change your view of the matrix',
'Are the human people the ones who started the war',
'Is AI a bad thing?'
]
The added (?!$) specifies that you split only when you do not have not reached the end of the line yet. Unfortunately, I am not sure the trailing delimiter on the last sentence can be reasonably removed without doing something like result[-1] = result[-1][:-1].
You can use filter to remove the empty elements
Ex:
import re
text = """The first time you see The Second Renaissance it may look boring. Look at it at least twice and definitely watch part 2. It will change your view of the matrix. Are the human people the ones who started the war? Is AI a bad thing?"""
def sent_tokenize(text):
sentences = re.split(r"[.!?]", text)
sentences = [sent.strip(" ") for sent in sentences]
return filter(None, sentences)
print sent_tokenize(text)
Any ideas on how to remove the extra '' at the end of my current
output?
You could remove it by doing this:
sentences[:-1]
Or faster (by ᴄᴏʟᴅsᴘᴇᴇᴅ)
del result[-1]
Output:
['The first time you see The Second Renaissance it may look boring', 'Look at it at least twice and definitely watch part 2', 'It will change your view of the matrix', 'Are the human people the ones who started the war', 'Is AI a bad thing']
You could either strip your paragraph first before splitting it or filter empty strings in the result out.

Removing "\n"s when printing sentences from text file in python?

I am trying to print a list of sentences from a text file (one of the Project Gutenberg eBooks). When I print the file as a single string string it looks fine:
file = open('11.txt','r+')
alice = file.read()
print(alice[:500])
Output is:
ALICE'S ADVENTURES IN WONDERLAND
Lewis Carroll
THE MILLENNIUM FULCRUM EDITION 3.0
CHAPTER I. Down the Rabbit-Hole
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversations?'
So she was considering in her own mind (as well as she could, for the
hot d
Now, when I split it into sentences (The assignment was specifically to do this by "splitting at the periods," so it's a very simplified split), I get this:
>>> print(sentences[:5])
["ALICE'S ADVENTURES IN WONDERLAND\n\nLewis Carroll\n\nTHE MILLENNIUM FULCRUM EDITION 3", '0\n\n\n\n\nCHAPTER I', " Down the Rabbit-Hole\n\nAlice was beginning to get very tired of sitting by her sister on the\nbank, and of having nothing to do: once or twice she had peeped into the\nbook her sister was reading, but it had no pictures or conversations in\nit, 'and what is the use of a book,' thought Alice 'without pictures or\nconversations?'\n\nSo she was considering in her own mind (as well as she could, for the\nhot day made her feel very sleepy and stupid), whether the pleasure\nof making a daisy-chain would be worth the trouble of getting up and\npicking the daisies, when suddenly a White Rabbit with pink eyes ran\nclose by her", "\n\nThere was nothing so VERY remarkable in that; nor did Alice think it so\nVERY much out of the way to hear the Rabbit say to itself, 'Oh dear!\nOh dear! I shall be late!' (when she thought it over afterwards, it\noccurred to her that she ought to have wondered at this, but at the time\nit all seemed quite natural); but when the Rabbit actually TOOK A WATCH\nOUT OF ITS WAISTCOAT-POCKET, and looked at it, and then hurried on,\nAlice started to her feet, for it flashed across her mind that she had\nnever before seen a rabbit with either a waistcoat-pocket, or a watch\nto take out of it, and burning with curiosity, she ran across the field\nafter it, and fortunately was just in time to see it pop down a large\nrabbit-hole under the hedge", '\n\nIn another moment down went Alice after it, never once considering how\nin the world she was to get out again']
Where do the extra "\n" characters come from and how can I remove them?
If you want to replace all the newlines with one space, do this:
import re
new_sentences = [re.sub(r'\n+', ' ', s) for s in sentences]
You may not want to use regex, but I would do:
import re
new_sentences = []
for s in sentences:
new_sentences.append(re.sub(r'\n{2,}', '\n', s))
This should replace all instances of two or more '\n' with a single newline, so you still have newlines, but don't have "extra" newlines.
If you want to avoid creating a new list, and instead modify the existing one (credit to #gavriel and Andrew L.: I hadn't thought of using enumerate when I first posted my answer):
import re
for i, s in enumerate(sentences):
sentences[i] = re.sub(r'\n{2,}', '\n', s)
The extra newlines aren't really extra, by which I mean they are meant to be there and are visible in the text in your question: the more '\n' there are, the more space there is visible between the lines of text (i.e., one between the chapter heading and the first paragraph, and many between the edition and the chapter heading.
You'll understand where the \n characters come from with this little example:
alice = """ALICE'S ADVENTURES IN WONDERLAND
Lewis Carroll
THE MILLENNIUM FULCRUM EDITION 3.0
CHAPTER I. Down the Rabbit-Hole
Alice was beginning to get very tired of sitting by her sister on the
bank, and of having nothing to do: once or twice she had peeped into the
book her sister was reading, but it had no pictures or conversations in
it, 'and what is the use of a book,' thought Alice 'without pictures or
conversations?'
So she was considering in her own mind (as well as she could, for the
hot d"""
print len(alice.split("."))
print len(alice.split("\n"))
It all depends the way you're splitting your text, the above example will give this output:
3
19
Which means there are 3 substrings if you were to split the text using . or 19 substrings if you splitted using \n as separator. You can read more about str.split
In your case you've splitted your text using ., so the 3 substrings will contain multiple newlines characters \n, to get rid of them you can either split these substrings again or just get rid of them using str.replace
The text uses newlines to delimit sentences as well as fullstops. You have an issue where just replacing the new line characters with an empty string will result in having words without spaces between them. Before you split alice by '.', I would use something along the lines of #elethan's solution to replace all of the multiple new lines in alice with a '.' Then you could do alice.split('.') and all of the sentences separated with multiple new lines would be split appropriately along with the sentences separated with . initially.
Then your only issue is the decimal point in the version number.
file = open('11.txt','r+')
file.read().split('\n')

Splitting individual sentence to list

I am asking on how to make individual lists. Not how to find a substring as marked duplicated for.
I have the following file
'Gentlemen do not read each others mail.' Henry Stinson
'The more corrupt the state, the more numerous the laws.' Tacitus
'The price of freedom is eternal vigilance.' Thomas Jefferson
'Few false ideas have more firmly gripped the minds of so many intelligent men than the one that, if they just tried, they could invent a cipher that no one could break.' David Kahn
'Who will watch the watchmen.' Juvenal
'Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.' John Von Neumann
'They that give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety.' Benjamin Franklin
'And so it often happens that an apparently ingenious idea is in fact a weakness which the scientific cryptographer seizes on for his solution.' Herbert Yardley
I am trying to convert each sentence to a list so that when I search for the word say "Gentlemen" it should print me the entire sentence.
I am able to get the lines to split but I am unable to convert them to individual list. I have tried a few things from the internet but nothing has helped so far.
here is what
def myFun(filename):
file = open(filename, "r")
c1 = [ line for line in file ]
for i in c1:
print(i)
you can use in to search a string or array, for example 7 in a_list or "I" in "where am I"
you can iterate directly over a file if you want
for line in open("my_file.txt")
although to ensure it closes people recommend using a context manager
with open("my_file.txt") as f:
for line in f:
that should probably at least get you going in the right direction
if you want to search case insensitive you can simply use str.lower()
term.lower() in search_string.lower() #case insensitive
Python strings have a split() method:
individual_words = 'This is my sentence.'.split()
print(len(individual_words)) # 4
Edit: As #ShadowRanger mentions below, running split() without an argument will take care of leading, trailing, and consecutive whitespace.

String Replacement and Matching in Python 2

I have user posts that I would like to match up with a predetermined list of patterns(see example). If the post matches a pattern, I would like to write the post and the pattern to a file. What is the best way to do this? So far I've only thought of brute forcing it with 4 for loops and then doing some comparisons. I already have the lists of all the data I need, below are just some very simple examples to give you an idea of what I am looking for.
Example
Posts:
posts =['When I ate at McDonald\'s, I felt sick.',
'I like eating at Burger King.',
'Wendy\'s made me feel happy.']
Pattern:
patterns = ['When I ate at [RESTAURANT]',
'I like eating at [RESTAURANT]',
'[RESTAURANT] made me feel [FEELING]',
'I felt [FEELING]']
Lists:
restaurant_names = ['McDonald\'s', 'Burger King', 'Wendy\'s']
feelings = ['happy', 'sick', 'tired']
OutputFile:
When I ate at [RESTAURANT], When I ate at McDonald's, I felt sick.
I felt [FEELING], When I ate at McDonald's, I felt sick.
[RESTAURANT] made me feel [FEELING], Wendy's made me feel happy.
I like eating at [RESTAURANT], I like eating at Burger King.
-Sorry for the formatting, but this is my first post on stackoverflow after lurking for a while. Thanks in advance for the help!
How about something like this:
>>> sentences = ["When I ate at McDonald's, I felt sick.", 'I like eating at Burger King.',
"Wendy's made me feel happy."]
>>> patterns = {"McDonald's": "[RESTAURANT]", "Burger King": "[RESTAURANT]",
"Wendy's": "[RESTAURANT]", "happy": "[FEELING]", "sick": "[FEELING]",
"tired": "[FEELING]"}
Then you can do
>>> for sentence in sentences:
... replaced = sentence
... for pattern in patterns:
... if pattern in sentence:
... replaced = replaced.replace(pattern, patterns[pattern])
... print sentence
... print replaced
...
When I ate at McDonald's, I felt sick.
When I ate at [RESTAURANT], I felt [FEELING].
I like eating at Burger King.
I like eating at [RESTAURANT].
Wendy's made me feel happy.
[RESTAURANT] made me feel [FEELING].
This still needs some work (for example, right now, the word carsick would become car[FEELING]), and you might want to avoid all the repetition in the patterns values by creating another list of replacement texts that you can refer to by index, but perhaps this is enough to get you started?
I'm not sure I understand. Could you please post the exact code you have so far, what you intend to do and why? Thanks.
In general, there are 4 alternatives:
1) Use a single, but complex, RegEx pattern and strict lists
r"(When I ate at (?P<rest1>McDonald's|Burger King|Wendy's), I felt (?P<feel1>happy|sick|tired)\.)|(I like eating at (?P<rest2>McDonald's|Burger King|Wendy's)\.)"
Analysis of the named capture groups rest1, feel1, rest2 would allow you to determine what sentence type was used if you need it. Otherwise, you can output the whole match. The pattern can, of course, be assembled programatically from your lists. Just be careful of using re.escape() when concatenating elements.
2) Use a single, but complex, RegEx pattern and loose lists
r"(When I ate at (?P<rest1>[^,]+), I felt (?P<feel1>[a-z]+).)|(I like eating at (?P<rest2>[^.]+)\.)"
This has the advantage that you can capture new restaurant names, feelings, etc. The disadvantage is dependency on punctuation / grammar. Example: the first pattern would not recognize a restaurant name with an embedded , .
3) Do what you are probably already doing. Natural language analysis is much more complex than what RegEx's can do by themselves.
4) If it's not just about a few fixed patterns, but about analyzing the meaning of a post regardless of specific wording, then you should use NLTK as other posters have suggested.

Categories

Resources