Remove punctuation from a list using loops-Python3 - loops

So what I'm trying to do is create a function that reads in a list and create a new list without the punctuation, using loops.
So far, I've got:
list=["This:","is","a","list."]
def depunctuate():
for i in range(0,len(list),1):
list1=""
for j in range(0,len(list[i]),1):
if(list[i][j] !=['(',')','?',':',';',',','.','!','/','"',"'"]):
list1+=list1[i][j]
cleanList+=[list1]
return cleanList
depunctuate()
So what I'm looking for it to return is "This is a list"
However I'm getting
Traceback (most recent call last):
File "depunctuate.py", line 10, in <module>
depunctuate()
File "depunctuate.py", line 7, in depunctuate
tokens1 += tokens1[i][j]
IndexError: string index out of range
Any help is appreciated, thanks!

clean_l = [s.strip(".:;,'\"?!/") for s in l]
This will remove leading and trailing punctuation chars.

Related

Adding prefix to existing array

I am trying to add suffix to an existing array. Below is my code
print('a' + [10, 100])
With this I am getting below error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "list") to str
Could you please help hoe to do that? I could use some for loop but I believe there may be more straightforward way to achieve the same.
You can create a new concatenated array as:
>>> ['{0}{1}'.format('a', num) for num in [10, 100]]
['a10', 'a100']
Read String format and List Comprehensions from doc.
If I understand your question, you want a new string array (list). You could try this:
new_lst = ['a'+str(x) for x in [10, 100]] # just use string concatentation

dict type numpy.AxisError: axis -1 is out of bounds for array of dimension 0

I am not able to figure out how to fix this error when I run my python code. This is the entire error
Loading all_data
type of alldata <class 'dict'>
Sorting these keys dict_keys([0, 1, 2, 3, 4, 5])
Traceback (most recent call last):
File "test.py", line 48, in <module>
keys_sorted = np.sort(all_data.keys())
File "/home/MAHEUNIX/anaconda3/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line 934, in sort
a.sort(axis=axis, kind=kind, order=order)
numpy.AxisError: axis -1 is out of bounds for array of dimension 0
MAHEUNIX#WGSHA-LAB-005:/
This is the corresponding code code:
print("Loading all_data")
all_data = load_dataset()
print("type of alldata",type(all_data),"\n")
print ("Sorting these keys", all_data.keys(),"\n\n")
keys_sorted = np.sort(all_data.keys())
print("keys sorted successfully\n")
train_idx, valid_idx = train_test_split(all_data.keys(), train_size = 0.9)
print (train_idx)
What is happening?

How to add numbers in an array stored in a file python

So I am trying to add numbers stored in a variable that is saved in a file.
if rw == "s":
fo = open("foo.txt", "w")
while int(count) != 0:
x = input("Input a number for storage ")
count = int(count) - 1
test.append(int(x))
print("")
fo.write("%s" % test)
fo.close()
fo = open("foo.txt", "r")
add = int(fo.readlines(1)) + int(fo.readlines(2))
I do not quite understand how the last part works. The error I get is the following:
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
The content of the file looks something like this:
[6, 7, 8, 9, 5, 4, 3]
Any help would be appreciated
If you want to select the first and second value of the list and add them together do this
content = fo.readlines(1)
content = content[0].replace('[', '').replace(']', '')
numbers = content.split(", ")
add = int(numbers[0]) + int(numbers[1])
Explanation:
readlines reads all the lines in the file and returns a list.
readlines(index) will return a list with only the selected line. Either case, you can't call int() on it.

splitting an array of string into individual elements

['2,3', '1,2,3', '4,5,6', '2,3', '10,11', '13,14,15', 'END']
Instead of how this array looks now, I need it to look like this:
[2,3,1,2,3,4,5,6,2,3,etc...]
I also cannot figure out, or even if there is a way to, separate the array of strings so that they are not strings and instead integers.
This is my read method and how it separated my txt file
def read_file():
with open('extra.txt') as fp:#read file
lines = fp.read().split();
fp.close(); #close file
return lines; #return lines to main function
You can do it in one go with a list comprehension, using str.split() to split the strings by comma and int() to convert to integers:
In [1]: l = ['2,3', '1,2,3', '4,5,6', '2,3', '10,11', '13,14,15', 'END']
In [2]: [int(number) for item in l[:-1] for number in item.split(",")]
Out[2]: [2, 3, 1, 2, 3, 4, 5, 6, 2, 3, 10, 11, 13, 14, 15]
l[:-1] to skip the last END element.
Also, here is a way to read and wrap the head around nested list comprehensions:
How to read aloud Python List Comprehensions?
If your old_list is your list containing the above strings,
old_list.remove('END')
new_list = []
for i in old_list:
sp = i.split(',')
for j in sp:
new_list.append(j)

Python, loop program

Can someone tell me what i am doing wrong? I am writing a program using loops in Python 3.x, but when i execute program i am getting a traceback error:
multiple of 13 is 195 and factors are as follows
Traceback (most recent call last):
File "C:/Users/Darlene/Desktop/Chapter 4/program4_2.py", line 19, in
list1.append(j)
AttributeError: 'dict' object has no attribute 'append'
this is the code i entered:
def main():
for i in reversed(list(range(100,201))):
if i%13==0:
print("multiple of 13 is",i,"and factors are as follows")
list1 = {}
for j in list(range(2,i+1)):
if i%j == 00:
list1.append(j)
print(list1)
main()
As commented by Luke Park, list1 = {} will declare a dictionary. What you need is list1 = [].
Also, range will already return a range type that can be handled by most methods and loops so there's no need to cast it to a list.
list1 must be an list like so...
list1 = []
you defined it as an dict, and as python said
'dict' object has no attribute 'append'

Resources