I am trying to append the list to itself but it says "takes exactly one argument"
I have tried using other variables to store the splited line.
testfile = open(r'''C:\Users\shawa\Desktop\sampleg102.txt''' ,'r')
print(testfile)
word=list
for line in testfile:
line = line.lstrip()
word = word.append([1])
print(word)
and the error is
E:\vscode.source> python -u "e:\vscode.source\python\countingWords.py"
<_io.TextIOWrapper name='C:\\Users\\shawa\\Desktop\\sampleg102.txt'
mode='r' encoding='cp1252'>
Traceback (most recent call last):
File "e:\vscode.source\python\countingWords.py", line 7, in <module>
word = word.append([1])
TypeError: append() takes exactly one argument (0 given)
To explain the first mistake, take a look at this:
>>> list
<class 'list'>
>>> word = list
>>> word
<class 'list'>
>>> word = list()
>>> word
<list object at 0x...>
At the moment, you have only assigned the name list to the name word. You need to call the list constructor to actually create the list. Now, the method list.append() modifies the list in-place. It returns None and you don’t need to re-assign it.
word = list()
# word = '' works too
for line in testfile:
line = line.lstrip()
word.append([1])
print(word)
Your code will print a list of lists of 1s at the moment. If you meant to append the lines of the file, use
word.append(line)
Note that it’s preferable to use the literal [] empty list syntax rather than calling list() as it makes it very clear what is being created.
You are looking for word=list() not word=list. list is just a keyword, list() instantiates
You need to do this if you are trying to append line to list. In your code you are appending only [1] to the list word.
testfile = open(r'''C:\Users\shawa\Desktop\sampleg102.txt''' ,'r')
print(testfile)
word=list()
for line in testfile:
line = line.lstrip()
word.append(1) #or word.append(line[1]) according to use case
print(word)
Related
im an beginner in python. I dont understand the Error. Please can you help me?
import fileinput
ersetzendic = {
"abc":"TESTabc",
"ABC":"TESTABC",
"qwertz":"TESTqwertz",
"wtf":"TESTwtf",
"wtfee":"TESTwtf2"
}
for line in fileinput.input("readme.txt", inplace=True):
for sonicsyntax in ersetzendic:
ersetzendic = ersetzendic[sonicsyntax]
line = line.replace(sonicsyntax,ersetzendic)
print(line, end="" )
TypeError: string indices must be integers
when you write ersetzendic = ersetzendic[sonicsyntax] you are trying to access an str by a value that is not an int.
By the looks of it may be a tuple of (key, value) from your dict ersetzendic.
The code is (unnecessarily) overwriting the variable: ersetzendic in the line:
ersetzendic = ersetzendic[sonicsyntax]
so instead of an array of strings it turns into a string on the first iteration, and in the second iteration we're trying to access an index of that string using a string as a key - which is why it fails.
We can modify the last 3 lines from:
for sonicsyntax in ersetzendic:
ersetzendic = ersetzendic[sonicsyntax]
line = line.replace(sonicsyntax,ersetzendic)
to:
for sonicsyntax in ersetzendic:
line = line.replace(sonicsyntax, ersetzendic[sonicsyntax])
As far as I understand, you want to replace the words in a file which contains any of the keys in ersetzendic with their corresponding value in the dict. In your solution, the produced error was occurred due to this segment:
for sonicsyntax in ersetzendic:
ersetzendic = ersetzendic[sonicsyntax]
With this, in the first iteration, you took a key from ersetzendic and reassigned ersetzendic taking the corresponding value of it. So that ersetzendic is now overwritten with a String value, that is not a dict anymore.
So, in the next iteration, when you're trying to repeat the thing, as ersetzendic is a string, accessing ersetzendic[something] is nothing but trying to accessing a character of specific index. Hence you're getting the error:
TypeError: string indices must be integers
However, you can take each line from the file, then each key of the dict ersetzendic and do a simple line.replace(target, replacingString) for your job. So, you can change the implementation as below:
for line in fileinput.input("readme.txt", inplace=True):
for key in ersetzendic:
line = line.replace(key,ersetzendic[key])
print(line, end="" )
The error you are facing is cause of the line line = line.replace(sonicsyntax,ersetzendic) here ersetzendic is a string value which is one of the values stored in the dictionary cause of the line ersetzendic = ersetzendic[sonicsyntax] which changes your dictionary ersetzendic to a string.
And you can not use str values to access strings.
I read in the comments about what you want to do.
Here is how to fix it:
import fileinput
ersetzendic = {
"abc":"TESTabc",
"ABC":"TESTABC",
"qwertz":"TESTqwertz",
"wtf":"TESTwtf",
"wtfee":"TESTwtf2"
}
with fileinput.input(files=("readme.txt",), inplace=True) as input: # using the context manager is a better way to read lines using the FileInput object
for line in input:
for sonicsyntax in ersetzendic:
replacement_text = ersetzendic[sonicsyntax] # store the value of the text to be reolaced in a new variable
line = line.replace(sonicsyntax,replacement_text) # pass the key as the first argument and the replacement text as the second
print(line,end='')
This is what readme.txt looks like before the execution of the code:
abc
ABEABC
wtfrrrrrwtf
wtfgwtfee
qwertyqweertz
This is the file content after the code is executed:
TESTabc
ABETESTABC
TESTwtfrrrrrTESTwtf
TESTwtfgTESTTESTwtf2
qwertyqweertz
item is most likely a string in your code; the string indices are the ones in the square brackets. So I'd first check your data variable to see what you received there; I guess that data is a list of strings (or at least a list containing at least one string) while it should be a list of dictionaries.
If you do not want to use file input module. Then I have an easy solution. Look at this example -
txt file:
abc
ABC
qwe
Code:
with open('file.txt','r') as f: # Read The file
lst = f.read().split()
for i in ersetzendic: # Replace desired elements
lst = [ersetzendic[i] if x==i else x for x in lst]
with open('1.txt','w') as f: # Write to file
for i in lst:
f.write(i+'\n')
Result in .txt file:
TESTabc
TESTABC
qwe
I think you can implement this in your code!
The following code returns a list, e.g. <class 'list'> in python. Everything I do to access that list fails
indexing list fails,
enumerating list fails
example if I just print(s)
['0.5211', '3.1324']
but if I access the indices
Traceback (most recent call last):
File "parse-epoch.py", line 11, in <module>
print("losses.add({}, {})".format(s[0], s[1]))
IndexError: list index out of range
Why can't I access the elements of the list?
import re
with open('epoch.txt', 'r') as f:
content = f.readlines()
content = [x.strip() for x in content]
for line in content:
s = re.findall("\d+\.\d+", line)
#print(s)
print("losses.add({}, {})".format(s[0], s[1]))
You should check what print(s) outputs again. Your issue is likely with a line where s does not contain a list with 2 values. If those values do not exist, then you cannot use them.
Here's my sample code for a programming problem asking to split a string and sort the individual words to avoid duplicates. I know that this code is 100% correct, but I'm not really sure what the purpose of lst = list() line of code is?
How does the program know to put the file romeo in the list?
fname = input("Enter file name: ")
romeo = open(fname)
lst = list()
for line in romeo:
line = line.rstrip()
line = line.split()
for e in line:
if e not in lst:
lst.append(e)
lst.sort()
print(lst)
Maybe you are confused with iteration over the file. Iteration allows us to treat the file as a container which can be iterated just like we do for any other container like list or set or dict.items().
Also lst = list() means lst = []. This has got nothing to do with file iteration.
See below for more insights:
# the following line stores your input in fname as a str
fname = input("Enter file name: ")
# the following line opens the file named fname and stores it in romeo
romeo = open(fname)
# next line creates an empty list through the built in function list()
lst = list()
# now you go through all the lines in the file romeo
# each word is assigned to the variable line sequentially
for line in romeo:
# strip the line of evntual withespaces at the end of the string
line = line.rstrip()
# split the string on withespaces and stores each element
# of the splitted string in the list line which will then contain every
# word of the line.
line = line.split()
# now you go through all the elements in the list line
# each word is assigned to e sequentially
for e in line:
# now if the word is not contained in the list lst
if e not in lst:
# it inserts the word to the list in the last postion of the list lst.
lst.append(e)
# sort the list alphabetically
lst.sort()
print(lst)
Some notes:
you would probably want to add romeo.close() at the end of the script to close the file
it is important to note that not all the file will be stored in the lst list. Each word will be stored there only once thanks to if e not in lst:
List is a python object. Type help(list) in your interpreter. You would see your screen
Usually for some programming languages calling className() would create object of the type class. For example in C++
class MyClass{
var declarations
method definitions
}
MyObj=MyClass()
The MyObj in above code is object for your class MyClass. Apply same thing for your code lst is object type of list class that is predefined in Python which we call it as builtin data structure.
So your above lst definition would initialize lst to be a empty list.
The help section shows two types of constructors for list class those are used in different ways. The second type of constructor
list(iterable)
would create a list with already created sequence. For example
tuple1=(1,'mars')
new_list=list(tuple1)
print(new_list)
would create new list new_list using the tuple which is a iterable.
The purpose of lst = list() is to create an instance of list called lst.
You could also replace it by
lst = []
it's exactely the same.
The line lst.append(e) is filling it. Here more about the append method
Here is what I want
read large JSON file(4.8MB)
replace specific words to new words
make new file then write line to new file
Here is my code.
def replaceString(input,replace_list): #read one line, and in that line, replace string in replace_list[0] with string in replace_list[1]
new_string = input
for i in range(len(replace_list)):
new_string = new_string.replace(replace_list[i][0], replace_list[i][1])
return new_string
input_f = open("ko_ko.json",'r') #very long file
output_f = open("new_ko_ko.json",'w')
replace_list = [["`","'"],["'"],[" !","!"],[" ?","?"]] #[ ["string to replace", "string to be replaced"] , ... ]
input_line = input_f.readlines()[0]
new_lines = replaceString(input_line,replace_list)
output_f.write(new_lines)
I debugged program keep showing following error
Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 /Users/jaegu/PycharmProjects/newJSON/makeJSON.py
Traceback (most recent call last):
File "/Users/jaegu/PycharmProjects/newJSON/makeJSON.py", line 13, in <module>
new_lines = replaceString(input_line,replace_list)
File "/Users/jaegu/PycharmProjects/newJSON/makeJSON.py", line 4, in replaceString
new_string = new_string.replace(replace_list[i][0], replace_list[i][1])
IndexError: list index out of range
One of your replace_list elements is a list with just one element: ["'"]. There is no second element in that list so you get an exception. Presumably you wanted that to be ["", "'"].
Some other remarks:
Use tuples for your pairs; the pairs don't need to be mutable, using tuples lets you catch bugs earlier.
Don't use range() when you can loop directly over your pairs:
for old, new in replace_list:
new_string = new_string.replace(old, new)
I don't understand why I'm getting this message:
Traceback (most recent call last):
File "/Users/rrmenon/Desktop/untitled text 4.py", line 5, in
list=fh.rstrip().split()
AttributeError: 'file' object has no attribute 'rstrip'
fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
list=fh.rstrip().split()
if word in lst: continue
lst.append(word)
lst.sort()
print lst
I'm trying to get all words in these strings (four or five sentences), copied in together in one list. What my Coe currently does (edited based on the suggestions below), is return each sentence as a separate list within a list. How Do I combine the words in the sentence?
The error is pretty clear: fh is a file object, which doesn't have a rstrip method.
Looks like you want line.rstrip() instead.
The message is very clear: you're trying to do fh.rstrip(), but rstrip works on strings, not files; what you probably wanted to do is:
list = line.rstrip().split()