'Finding whether all characters in a for loop match a requirement(s)
I have a list; list_words_punc which is a list of all the words in an input() using the split(). I then have another list; list_words which is a list of all the words in that same input() but without their punctuation (I.e .,?!). sentence is the input(). I want the program to check for all words in list_words_punc that every letter is a letter and it all gets appended to my new list list_words; any other punctuation is disbanded. The error I'm having is that if I use for s in l: if s.isalpha() and then append that to my new list, the list will be appending the letters as separate words instead of appending the same words from sentence just without punctuation. Is there any way to append the words?
list_words_punc=sentence.split()
list_words=[]
for l in list_words[]:
for s in l:
if s.isalpha():
Example just if I was unclear:
sentence="How, are you?"
list_words_punc=sentence.split()
list_words=[]
for l in list_words[]:
for s in l:
if s.isalpha():
I get:
["H","o","w"," ",...]
Solution 1:[1]
You could use regex to achieve this
re.findall()returns all non-overlapping matches of pattern in string, as a list of strings.\wrepresents a single word character\w+means one or more of a word character
Hope you understood.
Example:
Code
import re
sentence="How, are you?"
list_words = re.findall(r'\w+', sentence)
print(list_words)
Output
['How', 'are', 'you']
Solution 2:[2]
Basically what you are doing is appending at the end. The operation of appending always creates a new index and appends that value at that index. So, what you do is something like this.
sentence="How, are you?"
list_words_punc=sentence.split()
new_words=[]
index=0
for l in list_words_punc:
word=''
print(l)
for s in l:
if s.isalpha():
word+=s
else:
new_words.append(word)
word=''
if word!='':
new_words.append(word)
word=''
print(new_words)
So, you don't append character by character, instead create and store in an index (it is inefficient), but it works and removes all the punctuation and the list new_words has the words without punctuation
Solution 3:[3]
First of all you are iterating on list assigned none that is wrong itself Now answering question you just need to append each character at the end of string.
sentence="How, are you?"
list_words_punc=sentence.split()
list_word=[]
for word in list_words_punc:
s=""
for c in word:
if c.isalpha():s=s+c
list_word.append(s)
print (list_word)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abhi_J |
| Solution 2 | Muhammad Ahmed |
| Solution 3 | Ayan Khan |
