python 3.x - substitute of sum function

I am new to Python and trying to solve a task while reading the content of a text file but getting the message: ''float' object is not iterable' when trying to sum all the outputs from the variable 'sppos'.All the outputs are numbers bigger than 0 of type 0.xxxxAlso trying to have the total of all values without using the sum function.Any hints which other function could be used?fname=input('Enter a file name:')fhand=open(fname)count=0for line in fhand: line=line.rstrip() if not line.startswith("X-DSPAM-Confidence:") : continue count=c...Read more

Python Connection pymysql

I'm new in python and I'm facing some issues with my script. I have a def for connection with my db and a model to insert data into it.This is my connection:def conexao(): import pymysql config = { 'user': 'root', 'password': 'admin', 'host': '', 'database': 'megasena' } try: conection = pymysql.connect(**config) cursor = conection.cursor() return cursor except pymysql.InternalError as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print('Dados de...Read more

python 3.x - python3 wx.TreeCtrl - how to iterate through several levels

I have a treectrl structure which is populated from an external search of an open data set hosted by our municipal government. The data pertains to business licenses and is requested using Pandas and Sodapy. The tree is populated as follows:for index, row in results_df.iterrows(): tradename = row['tradename'] address = row['address'] licTypes = row['licencetypes'] comm = row['comdistnm'] jobSts = row['jobstatusdesc'] jobCrt = row['jobcreated'] lng = row['longitude'] lng = str(lng) l...Read more

python 3.x - how to solve this error with lambda and sorted method when i try to make sentiment analysis (POS or NEG text)?

Input code: best = sorted(word_scores.items(), key=lambda w, s: s, reverse=True)[:10000]Result: Traceback (most recent call last):File "C:\Users\Sarah\Desktop\python\", line 78, in <module>best = sorted(word_scores.items(), key=lambda w, s: s, reverse=True)[:10000]TypeError: <lambda>() missing 1 required positional argument: 's'How do I solve it?...Read more

python 3.x - IP Address Iteration, Why do I not have to nestle 'x' in a for loop?

I am completing the python masterclass challenge program 1. I understand everything from the solution until the very last line of code. We have to determine the number of segments and length of segments within a valid/invalid ip address. I understand that this will accurately display the number of segments and length of segments, but why doesn't the final line have to be nestled in a for loop? How can I just call an arbitrary 'x' from thin air? It is not in reference to any variable or str? I'm trying to understand the thought process of the sy...Read more

python 3.x - Changing a method name dynamically in a loop?

I am actually struggling while trying to change a method name within a loop. I am building a GUI with QT and I am facing the problem of repeating the same function but with a different name.Here is my code:from Config import Ui_Dialogclass Ui_Dialog_Useful(Ui_Dialog): def setupUi(self, widget): super().setupUi(widget) self.Sensitivity_filler() def Sensitivity_filler(self): self.Sensitivity_1.insertItems(0, ['10', '100', '1000']) self.Sensitivity_2.insertItems(0, ['10', '100', '1000']) self.Sensitivity_3....Read more

python 3.x - Index Error Problems

So I'm making a calculator that takes in a string and checks to see if it has certain words like add or subtract and then finding integers. However, in my current code, I run it and get this error message:Traceback (most recent call last): File "python", line 1, in <module> File "python", line 7, in calculatorIndexError: string index out of rangeThe code is typed out below.def calculator(string): if "add" in string or "Add" in string: total = 0 for i in range(len(string)): #loop for length of string try: ...Read more

python 3.x - Getting error in list assignment about index?

I recently started to study Python, and as I was trying to run a code from a book (with my modification) I got the error:IndexError: list assignment index out of rangein : `Names[len(Names)]=name`I read some questions with this error on web but can't figure it out.Names=[]num=0name=''while True : print('Enter the name of person '+str(len(Names)+1) + '(or Enter nothing to stop)') name=input() if name == '' : break Names[len(Names)]=nameprint('the person names are:')for num in range(len(Names)+1) : print(' '+Names[num])...Read more

python 3.x - how to extract href from <a> element using lxml cssselctor?

def extract_page_data(html):tree = lxml.html.fromstring(html)item_sel = CSSSelector('.my-item')text_sel = CSSSelector('.my-text-content')time_sel = CSSSelector('.time')author_sel = CSSSelector('.author-text')a_tag = CSSSelector('.a') for item in item_sel(tree): yield {'href': a_tag(item)[0].text_content(), 'my pagetext': text_sel(item)[0].text_content(), 'time': time_sel(item)[0].text_content().strip(), 'author': author_sel(item)[0].text_content()}I want to extract href but I am not able to extract it using t...Read more

python 3.x - how to extract href attribute of ‘a’ element using id= instead of class name

I have the following:<div id="header-author" class="some random class"> <a id="author-text" class="some random class" href="/page?id=232"> <span class="some random class"> Hello there </span> </a>and i want to extract only href attributes of id="author-text"i cant use class to extract because the class is used by other elements which has href links which i do not want to extracti have tried thissoupeddata = BeautifulSoup(my_html_code, "html.parser")my_data = soupeddata.fin...Read more

Pandas error in python 3.5.1

I am using python 3.5.1, Following shows dataimport pandas as pdimport quandldf = quandl.get('WIKI/GOOGL')print(df.head())I am doing followingimport pandas as pdimport quandldf = quandl.get('WIKI/GOOGL')df = df[['Adj. Open','Adj. High','Adj. Low','Adj. Close','Adj. Volume',]]df['HL_PCT'] = (df['Adj. High'] - df['Adj. Close']) / df['Adj. Close']*100.0df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. OPen']*100.0df = df[['Adj. Close','HL_PCT','PCT_change','Adj. Volume']]print(df.head())but its showing following error Traceback ...Read more

python 3.x - why is my second to last number not visible in output?

When running>>> a = np.linspace(0, 330, 330, 1, dtype=int)>>> print(a)[ 0, 1, 2, ..[skipped for readability].. 323, 324, 325, 326, 327, 328, 330])], dtype=intI expect the second last number to be 329 instead of 328. Why is this not the case? It's probably because that number in a float will be 328.99696049 but I do wonder how I can include it into my output, and if it does matter for my data purity when I do calculations on that number....Read more

python 3.x - KeyError with dictionaries

I was attempting to get the user to enter a city and the temperature which would be saved to a dictionary. However, Python keeps telling me that I'm getting a KeyError. Why is this happening and how do i fix this? Thank you.def main(): city = {} keepgoing = True while keepgoing: user = input("Enter city followed by temperature: ") for valu in user.split(): city[valu] = city[valu]+1 if user == "stop": keepgoing = False print(city)main()...Read more

dictionary - Python dictionaries formatting

Python3 I have a dictionary with alphabet count, shown belowa 24873b 5293c 7301d 15567e 38088f 6499g 7109h 20360i 20283j 751k 3207l 12780m 7686n 21510o 24944p 5275q 191r 16751s 18831t 30897u 9624v 2551w 8390x 439y 7139z 161and i want a function to print it as e 38088 i 20283 w 8390 b 5293 q 191 t 30897 s 18831 m 7686 p 5275 z 161 o 24944 r 16751 c 7301 k 3207 a 24873 d 15567 y 7139 v 2551 n 21510 l 12780 g 7109 j 751 h 20360 u 9624 f 6499 x 439 I tried taking keys and values into lists but is randomly changing as a dictionary is not ordered. ...Read more