How to fetch values in quotes using python?

How to fetch values in quotes using python?


xml_strg = """<?xml version="1.0"?>
<xml_api_reply version="1">
    <weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" >
        <forecast_information>
            <city data="Baton Rouge, LA"/>
            <postal_code data="baton rouge,la"/>
            <latitude_e6 data=""/>
            <longitude_e6 data=""/>
            <forecast_date data="2011-02-22"/>
            <current_date_time data="2011-02-22 20:06:59 +0000"/>
            <unit_system data="US"/>
        </forecast_information>
        <current_conditions>
            <condition data="Cloudy"/>
            <temp_f data="72"/>
            <temp_c data="22"/>
            <humidity data="Humidity: 73%"/>
            <icon data="/ig/images/weather/cloudy.gif"/>
            <wind_condition data="Wind: N at 5 mph"/>
        </current_conditions>
    </weather>
</xml_api_reply>
"""       

import xml.etree.cElementTree as et

root =  et.fromstring(xml_strg)
result = []
for elem in root.find('./weather/current_conditions'):
    if elem.tag in ('humidity', 'icon', 'wind_condition'):
        result.append(elem.get('data'))
print result

['Humidity: 73%', '/ig/images/weather/cloudy.gif', 'Wind: N at 5 mph']

'humidity data="Humidity: 73%" icon data="/ig/images/weather/cloudy.gif" wind_condition data="Wind: N at 5 mph"'

import re
re.findall('"(.+?)"', in_string)

#!/usr/bin/env python

from xml.etree.ElementTree import XML
import sys
data = """<?xml version="1.0"?>
<xml_api_reply version="1">
<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
    <forecast_information>
        <city data="Baton Rouge, LA"/>
        <postal_code data="baton rouge,la"/>
        <latitude_e6 data=""/>
        <longitude_e6 data=""/>
        <forecast_date data="2011-02-22"/>
        <current_date_time data="2011-02-22 20:06:59 +0000"/>
        <unit_system data="US"/>
    </forecast_information>
    <current_conditions>
        <condition data="Cloudy"/>
        <temp_f data="72"/>
        <temp_c data="22"/>
        <humidity data="Humidity: 73%"/>
        <icon data="/ig/images/weather/cloudy.gif"/>
    </current_conditions>
</weather>
</xml_api_reply>
"""

tree = XML(data)
conditions = tree.findall("weather/current_conditions")
results = []
for c in conditions:
    curr_results = {}
    for child in c.getchildren():
        curr_results[child.tag] = child.get('data')
    results.append(curr_results)

print results

<?xml version="1.0"?><xml_api_reply version="1"><weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0" ><forecast_information><city data="Baton Rouge, LA"/><postal_code data="baton rouge,la"/><latitude_e6 data=""/><longitude_e6 data=""/><forecast_date data="2011-02-22"/><current_date_time data="2011-02-22 20:06:59 +0000"/><unit_system data="US"/></forecast_information><current_conditions><condition data="Cloudy"/><temp_f data="72"/><temp_c data="22"/><humidity data="Humidity: 73%"/><icon data="/ig/images/weather/cloudy.gif"/><wind_condition data="Wind: N at 5 mph"/>

import re

with open('joeljames.txt','rb') as f:
    RE = ('humidity data="([^"]*)"/>'
          '<icon data="([^"]*)"/>'
          '<wind_condition data="([^"]*)"/>')
    print re.search(RE,f.read()).groups()

import re
print re.search(('humidity data="([^"]*)"/>'
                 '<icon data="([^"]*)"/>'
                 '<wind_condition data="([^"]*)"/>'),
                open('joeljames.txt','rb').read()).groups()

('Humidity: 73%', '/ig/images/weather/cloudy.gif', 'Wind: N at 5 mph')

import re
print dict(re.findall('(humidity data|icon data|wind_condition data)'
                      '="([^"]*)"/>',open('joeljames.txt','rb').read()))

{'humidity data': 'Humidity: 73%', 'icon data': '/ig/images/weather/cloudy.gif', 'wind_condition data': 'Wind: N at 5 mph'}

>>> from lxml import etree
>>> filePath = 'c:/test.xml'
>>> root = etree.parse(filePath)
>>> keypairs = dict((r.tag, r.get('data')) for r in root.xpath('//*[@data]'))

>>> print keypairs
{'city': 'Baton Rouge, LA', 'forecast_date': '2011-02-22', 'latitude_e6': '', 'l
ongitude_e6': '', 'temp_c': '22', 'humidity': 'Humidity: 73%', 'postal_code': 'b
aton rouge,la', 'unit_system': 'US', 'temp_f': '72', 'current_date_time': '2011-
02-22 20:06:59 +0000', 'condition': 'Cloudy', 'icon': '/ig/images/weather/cloudy
.gif'}

>>> print keypairs['humidity']
Humidity: 73%

Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.

Write a program which repeatedly reads numbers until the user enters “done”. Once “done” is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number, detect their mistake using try and except and print an error message and skip to the next number.



'''
sum1=0
total=0
average=0
a=raw_input('Enter a number:')
while a!='done':
    try:
        a=float(a)
        sum1=sum1+a
        total=total+1
    except:
        print "Please insert a number"
    a=raw_input("Enter a number:")
print "Sum:",sum1
print "Total:",total
print "Average:",float(sum/total)

Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.

Write another program that prompts for a list of numbers as above and at the end prints out both the maximum and minimum of the numbers instead of the average.




a=raw_input('Enter a number:')
min=a
max=a
while a!='done':
    try:
        a=float(a)
        if(float(a)>float(max)):
            max=a
        if(float(a)<float(min)):
            min=a
    except:
        print "Please insert a number"
    a=raw_input("Enter a number:")
print "Max:",max
print "Min:",min

How To Write a program in Python that asks user to input 5 lines of numbers. Your program should represent these lines as a table.

Write a program in Python that asks user to input 5 lines of numbers. Your program should represent these lines as a table.


#function that checks if n is float or not
def float_or_not(n):
    for char in n:
        if char == ".":
            return True

table = []

for i in range(5):
    numbers = input("Enter some numbers: ").split(" ")
    for x, y in enumerate(numbers):
        if float_or_not(y) == True:
            numbers[x] = float(y)
        else:
            numbers[x] = int(y)
    table.append(numbers)

print(table)

Write a function average() that takes no input but requests that the user enters a sentence, i.e. a string. Your function should return the average length of a word in the sentence.

Write a function average() that takes no input but requests that the user enters a sentence, i.e. a string. Your function should return the average length of a word in the sentence.


Usage:
>>> average()
Enter a sentence: Most modern calendars mar the sweet
simplicity of our lives by reminding us that each day
that passes is the anniversary of some perfectly
uninteresting event
5.115384615384615

So far I have this:

def average():
    wordCount = input('Enter a sentence: ')
    sum = 0
    if wordCount != 0:
        average = sum / wordCount
    else:
        average = 0
    return(average)

How to write a static python getitem method?

How to write a static python getitem method?



class A:
    @staticmethod
    def __getitem__(val):
        return "It works"

print A[0]

class MetaA(type):
    def __getitem__(cls,val):
        return "It works"

class A(object):
    __metaclass__=MetaA
    pass

print(A[0])
# It works

Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.

Write a function that reads the words in words.txt and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.



'''
f1=open('words.txt')
d1=dict()
i=0
for line in f1:
    words=line.split()
    for i in range(len(words)):
        d1[words[i]]=i
print d1
print 'abc' in d1