Utente:Nick84/Sandbox2

Da Wikipedia, l'enciclopedia libera.
Vai alla navigazione Vai alla ricerca

Codice per il progetto fisica[modifica | modifica wikitesto]

# coding: latin-1
import wikipedia # Import the wikipedia module
import catlib 
import pagegenerators
import re
import mysql_autoconnection

def main():
	global paginabibliografia 
	global manualinsert
	global citalibro_standard
	global citalibro
	citalibro=['cognome','nome','wkautore','coautori','curatore','altri','titolo','dataoriginale','annooriginale','meseoriginale','url','formato','datadiaccesso','annodiaccesso','mesediaccesso','edizione','data','anno','mese','editore',u'città','lingua','id','doi','pagine','capitolo','url_capitolo','citazione','cid']
	citalibro_standard={'nome':1,'cognome':2,'titolo':3,'anno':4,'editore':5,u'città':6}
	conn=set_connection()#Let's assure that the table isn't dirty
	conn.execute('TRUNCATE TABLE `librifisicawiki`')
	conn.close()
	paginabibliografia='Utente:Nick84/Sandbox'
	manualinsert='inserita manualemnte'
	site = wikipedia.getSite() # Taking the default site
	pages = [wikipedia.Page(wikipedia.getSite()]#let's load the old bibliography first
	gen = iter(pages)
	biblio_operation(gen)#Load templates in database and perform simple maintain op.
	cat = catlib.Category(site,'Categoria:Fisica')#Let's look in all the categories linked to the project
	gen = pagegenerators.CategorizedPageGenerator(cat, recurse=True)
	biblio_operation(gen)#as above
	bibliotext=create_biblio() #Ok we have all the books stored let's create a bibliography
	bibliopage=wikipedia.Page(wikipedia.getSite(), paginabibliografia)#switch back to the bibliography page and change it
	bibliopage.put(bibliotext.decode('utf-8'),'Bot: Aggiorno la bibliografia (Test come richiesto nella pagina di richiesta autorizzazioni)')#to do something real
	#wikipedia.output(bibliotext)#test only

def biblio_operation(gen):
	for page in gen:
		global pagename#This global variable is defined in order to know in which page the bot is operating when it finds a template. The callback function defined in wikipedia.replaceExecept cannot take this as a parameter
		global pagemodified#This global variable is defined in order to know if the do_other_mant bot has modified a page as that function gives back only the modified text 
		pagename = page.title() # Take the title of the page (not "[[page]]" but "page")
		wikipedia.output(u"Loading %s..." % pagename) # Please, see the "u" before the text
		try:
			text = page.get() # Taking the text of the page
		except wikipedia.NoPage: # First except, prevent empty pages
			text = ''
		except wikipedia.IsRedirectPage: # second except, prevent redirect
			wikipedia.output(u'%s is a redirect!' % pagename)
			continue
		except wikipedia.Error: # third exception, take the problem and print
			wikipedia.output(u"Some error, skipping..")
			continue     
		old= 'cita libro' #Search for instances of cita libro only
		pattern = '[' + re.escape(old[0].upper()) + re.escape(old[0].lower()) + ']' + re.escape(old[1:]) #I want to find it wheter is capitalized or not
		templateRegex = re.compile(r'\{\{ *([Tt]emplate:|[mM][sS][gG]:)?' + pattern + r'(?P<parameters>\s*\|.+?|) *}}', re.DOTALL) #Compile regex so to be faster
		wikipedia.replaceExcept(text, templateRegex, add_to_bibliography,['nowiki'])#wikipedia.replaceExcept allow me to define a callback function to handle the match plus i don't want to search templates that are enclosed in <nowiki>
		pagemodified=False#Set to False=not modified, if set = True then modified. This refer to the current page in the for cycle
		#text=do_other_mant(page,text)#As we have to access all the pages in all the subcategories it's useful to do some maintenance on them
		#if pagemodified :
			#page.put(text,'Bot: Inserisco il template portale (Test come richiesto nella pagina di richiesta autorizzazioni)') #For now the only mant task it's to add portale|fisica tmpl
			#wikipedia.output(text)

def add_to_bibliography(match):
	#This function is called by wikipedia.replaceExcept everytime a match (a template cita libro) is found
	CitedItem=match.group() #match.group() contains all the template
	CitedItem.strip()#Just in case i have some spaces
	key=create_bibliokey_from_template(CitedItem)#I want to create something I could use to do bibliographic comparison.
	if not is_in_libri(key): #Look if I already have something similar stored in my bibliography
		put_in_libri(key,CitedItem)	#If not then insert it
	else:
		chose_best_template(key,CitedItem) # If yes then compare what I already have to what I found in order to determine, if possible, which is the best one
	return match.group() #This is needed because this function is called by wikipedia.replaceExcept and the latter wait from this function a text to substitute the original template. return match.group() basically means substitute the template with the template itself

def create_bibliokey_from_template(CitedItem): 
	#Define a string in which i know what are the single pieces. It's a sort of template hash.
	#Otuput will be something like ISBN|Title|Name|Surname
	ISBN=cercaparametro(CitedItem,'id',citalibro_standard)
	if not ISBN: ISBN=''
	Titolo=cercaparametro(CitedItem,'titolo',citalibro_standard)
	if not Titolo: Titolo=''
	Nome=cercaparametro(CitedItem,'nome',citalibro_standard)
	if not Nome: Nome=''
	Cognome=cercaparametro(CitedItem,'cognome',citalibro_standard)
	if not Cognome: Cognome=''
	key=ISBN.strip()+'|'+Titolo.strip()+'|'+Nome.strip()+'|'+Cognome.strip() 
	return key

def is_in_libri(key):
	#I check against database if the book we found in the text is already in (the "hash" of the template is used for comparison)
	conn=set_connection()#Function used to connect to DB
	keyISBN=key.split('|')[0]#I select ISBN as it's useful for new books
	keytitolo=key.split('|')[1]#I select the title as is unique (at least we hope) and is mandatory
	keytitolo=re.sub('\'','\\\'',keytitolo)#This and the following allow the MySQL query to go ahead without problems related to ' and " that might appear in titles
	keytitolo=re.sub('\"','\\\"',keytitolo)
	ISBNlung=len(keyISBN)#Is the ISBN really defined?
	if ISBNlung>0:
		conn.execute('SELECT * from '+table+' where ISBN like CONVERT( _utf8 \''+keyISBN+'\'USING latin1 ) OR titolo like CONVERT( _utf8 \''+keytitolo+'\'USING latin1 )')#If we have an ISBN we have to search for it OR for the title
	else:
		conn.execute('SELECT * from '+table+' where titolo like CONVERT( _utf8 \''+keytitolo+'\'USING latin1 )')#On the contrary we search only for the title
	rowcount=conn.rowcount	#did we select anything?
	conn.close()#IMPORTANT!!! We cannot leave connections opened or the poor MySQL would feel a connectionache
	if rowcount > 0 :
		return True #Ok is in the database as we select something
	else:
		return False #There's no matching entry in the db

def put_in_libri(key,citeditem):
	#If we don't find the book in we put it in the db
	conn=set_connection()#see above
	keyISBN=key.split('|')[0]
	keytitolo=key.split('|')[1]
	keytitolo=re.sub('\'','\\\'',keytitolo)
	keytitolo=re.sub('\"','\\\'',keytitolo)
	citeditem=re.sub('\'','\\\'',citeditem) #the same as for title for the same reasons see above
	citeditem=re.sub('\"','\\\"',citeditem)
	altrepagine=pagename#we store this in order to know in the following steps where we found this template.
	conn.execute('INSERT INTO `'+table+'` (`ISBN`, `titolo`, `template`,`altrepagine`) VALUES (\''+keyISBN+'\',\''+keytitolo+'\',\''+citeditem+'\',\''+altrepagine+'\')')
	conn.close()

def chose_best_template(key,citeditem):
	#Ok we have already a template stored but which one is the best?
	#This function is a real mess be carefull
	conn=set_connection()#see above	
	keyISBN=key.split('|')[0]#see above
	keytitolo=key.split('|')[1]
	keytitolo=re.sub('\'','\\\'',keytitolo)
	keytitolo=re.sub('\"','\\\"',keytitolo)
	citeditem2=re.sub('\'','\\\'',citeditem)#We define a citeditem2 because we want to keep a plain version (i.e. without subs) to make comparisons
	citeditem2=re.sub('\"','\\\"',citeditem2)
	ISBNlung=len(keyISBN)#see above
	#now unlike in is_in_libri we select template and altrepagine from the db in order to take a diff between the old one and the new one. Altrepagine is needed later if we want to take a note regarding the fact that we found a similar but not prefectly matching template in a page.
	if ISBNlung>0:
		conn.execute('SELECT template,altrepagine from '+table+' where (ISBN like CONVERT( _utf8 \''+keyISBN+'\'USING latin1 ) OR titolo like CONVERT( _utf8 \''+keytitolo+'\'USING latin1 )) AND template != CONVERT( _utf8 \''+citeditem2+'\'USING latin1 ) ')
	else:
		conn.execute('SELECT template from '+table+' where titolo like CONVERT( _utf8 \''+keytitolo+'\'USING latin1 ) AND template != CONVERT( _utf8 \''+citeditem2+'\'USING latin1 ) ')
	#rowcount=conn.rowcount#This is not really needed
	conn.close()
	for record in conn.fetchall(): #We are selecting one record but this is needed to avoid exceptions 
		old=str(record[0].encode("utf-8")) #This was a horrible headache to find please leave it alone
		altrepagine=str(record[1].encode("utf-8"))#the same
		altrepaginearray=altrepagine.split('|')
		paginatemplate=altrepaginearray[0]#This is the page in which we took the saved template
		wikipedia.output(u'\n\n>>>>>Necessario intervento dell\'operatore per scegliere la versione migliore del template.\n Potrai indicare in seguito la necessita\' di rivedere il template che salvi integrandolo con informazioni prese dal template che non salvi.\n')
		wikipedia.showDiff(record[0],citeditem) #We are going to take a diff. Note regarding encodings that this is the only way it works leave it alone
		#I want to know what to do from an human being. Which template is the best?
		answer = wikipedia.inputChoice(u'Quale versione si desidera salvare?', ['Prima', 'Seconda','Voglio settare a mano tutti i parametri'], ['1', '2','V'], '1')
		#Let's warn the user if the old template that is trying to change came from the old biblio or was manually inserted before during the process
		if paginatemplate in (paginabibliografia, manualinsert) and answer=='2': 
			#Let's chose what's best to say
			if paginatemplate==paginabibliografia: 
				addtomessage='presente nella vecchia versione di '+paginabibliografia+'. '
			else: 
				addtomessage='stato compilato manualmente. '
			#This is the warning
			wikipedia.output(u'\n\n>>>>>!!!!!!!!!!!!!!!!!**********Attenzione il template salvato in memoria (numero 1) era '+addtomessage+'Se si salva la seconda versione la prima sara\' persa per sempre**********!!!!!!!!!!!!!!!!!\n')
			#Let's ask again the user in order to understand if he's sure
			answer = wikipedia.inputChoice(u'Conferma la versione che si desidera salvare?', ['Prima', 'Seconda','Voglio settare a mano tutti i parametri'], ['1', '2','V'], '1')
		if answer == '2' : #In this case I have to update the stored template with the new one
			conn=set_connection()
			#We're changing the saved template so we should also change the page in which the saved template reside. And we don't want any double references
			altrepagine=re.sub(pagename,'',altrepagine) #first we cancel any references already present to the page in which we found the is going to be saved template
			altrepagine=re.sub(paginatemplate,pagename,altrepagine) #then we change the page in which the saved template was found
			if ISBNlung>0: #Usual problem in selecting
				conn.execute('UPDATE `'+table+'` set `template`=\''+citeditem2+'\',`altrepagine`=\''+altrepagine+'\' WHERE (ISBN like CONVERT( _utf8 \''+keyISBN+'\'USING latin1 ) AND titolo like CONVERT( _utf8 \''+keytitolo+'\'USING latin1 )) LIMIT 1') #LIMIT  1 just in case of problems....
			else:
				conn.execute('UPDATE `'+table+'` set `template`=\''+citeditem2+'\',`altrepagine`=\''+altrepagine+'\' WHERE (titolo like CONVERT( _utf8 \''+keytitolo+'\'USING latin1 )) LIMIT 1')
			conn.close()
		if answer == 'v' : #Let's take the standard template and ask the user for every parameter. 
			nuovotemplate={}#This is where we are going to store any parameter's name and any value
			#Let's tell the user what are the rules to follow in order to play fairly
			wikipedia.output(u'\n\n>>>>>Se in entrambi i template il parametro e\' identico verra\' chiesto se confermare il valore o sostituirlo manualmente\n')
			wikipedia.output(u'>>>>>Altrimenti l\'operatore potra\' scegliere quale dei due tenere o se effettuare una sostituzione manuale\n')
			#let's iterate over the template parameters 
			for parametroattuale in citalibro:
				p1=cercaparametro(record[0],parametroattuale,citalibro_standard)#Search for a value for the parameter in the given template
				p2=cercaparametro(citeditem,parametroattuale,citalibro_standard)#as above
				if not p1 and not p2: #Ok we didn't found anything so it wasn't important and the user could manually edit the biblio after
					continue
				#At this point we know that in p1 or in p2 there's something valuable
				if not p1: p1='' #just in case the parameter was found in the second template but not in the first (we don't want to deal with exceptions and errors that are going to show if we try to use a boolean as if it were a string, do we?)
				if not p2: p2=''
				if p1==p2: #First case: the values are equal. Let's ask the user if he confirms the value or if he wants to manually edit it
					parametroanswer1 = wikipedia.inputChoice(u''+parametroattuale+':'+p1+'. Conferma o modifica ?', ['Conferma', 'Modifica'], ['C', 'M'], 'C')
					if parametroanswer1=='c':#confirmed....
						nuovotemplate[parametroattuale]=p1#....and stored
					else:#not confirmed
						parametroconfermato='m'#[m]odifiy=go on [c]onfirmed=stop and store it
						while parametroconfermato=='m': #So the user has the chance to change his mind
							parametroinserito=wikipedia.input(u'Inserire il valore per '+parametroattuale)#insert....
							parametroconfermato=wikipedia.inputChoice(u''+parametroattuale+':'+parametroinserito+'. Conferma o modifica ?', ['Conferma', 'Modifica'], ['C', 'M'], 'C')#....check....
						nuovotemplate[parametroattuale]=parametroinserito#...and stored
				else:#the values are different!!!! (OMG!!!!!)
					wikipedia.output(u''+parametroattuale+':')
					wikipedia.showDiff(p1,p2)#let's show the usual diff and ask the human being out there what to do
					parametroanswer1 = wikipedia.inputChoice(u'Mantenere 1 o 2 o modificare a mano? ?', ['1', '2','Modifica'], ['1','2','M'], 'C')
					#Do you want to keep 1,2 or do u want to use your hands and try to write something better?
					if parametroanswer1=='1':#kept1...
						nuovotemplate[parametroattuale]=p1#...and saved
					elif parametroanswer1=='2':#kept 2....
						nuovotemplate[parametroattuale]=p2#... and saved
					else:# waht a pity nothing was good let's wait for the user 
						parametroconfermato='m'#as above
						while parametroconfermato=='m':
							parametroinserito=wikipedia.input(u'Inserire il valore per '+parametroattuale)
							parametroconfermato=wikipedia.inputChoice(u''+parametroattuale+':'+parametroinserito+'. Conferma o modifica ?', ['Conferma', 'Modifica'], ['C', 'M'], 'C')
						nuovotemplate[parametroattuale]=parametroinserito
			testotemplate=compilatemplate('Cita libro',citalibro,nuovotemplate)#call a function that will write down the wikisyntax for the template
			testotemplate=re.sub('\'','\\\'',testotemplate)#let's make ready for MYSQL
			testotemplate=re.sub('\"','\\\"',testotemplate)
			altrepagine=re.sub(paginatemplate,manualinsert,altrepagine)#Let's remember that this version was manually inserted
			conn=set_connection()#MySQL here we go.... se above
			if ISBNlung>0: #Usual problem in selecting
				conn.execute('UPDATE `'+table+'` set `template`=\''+testotemplate+'\',`altrepagine`=\''+altrepagine+'\' WHERE (ISBN like CONVERT( _utf8 \''+keyISBN+'\'USING latin1 ) AND titolo like CONVERT( _utf8 \''+keytitolo+'\'USING latin1 )) LIMIT 1') #LIMIT  1 just in case of problems....
			else:
				conn.execute('UPDATE `'+table+'` set `template`=\''+testotemplate+'\',`altrepagine`=\''+altrepagine+'\' WHERE (titolo like CONVERT( _utf8 \''+keytitolo+'\'USING latin1 )) LIMIT 1')
			conn.close()		
		if not (paginatemplate==paginabibliografia or paginatemplate==manualinsert or answer=='v') or answer=='1': #The following will be shown only if the discharged template wasn't stored in the bibliography page or wasn't manually inserted or if the new template wasn't manually inserted (we hope that the user already inserted everything and that he doesn't to take note for the future)
			answer2 = wikipedia.inputChoice(u'Desideri indicare che il template salvato e\' da integrare con informazioni di quello scartato?', ['Si', 'No'], ['S', 'N'], 'N') #Now i want to know if you want a note that says that some info of the discarded template are useful
		else: #Fast way not to get any problem if we don't ask.
			answer2 = 'n'
		if answer2 == 's' : #if yes then append the current page in a string of other pages in which the template has been found before.
			if answer == '2' : 
				altrepagine=re.sub(paginatemplate,'',altrepagine)#We don't want to have any double ref.
				altrepagine=altrepagine+'|'+paginatemplate #We store the page in which the discarded templated was found
			if answer == '1' : 
				altrepagine=re.sub(pagename,'',altrepagine)
				altrepagine=altrepagine+'|'+pagename #We store this page.
			conn=set_connection()
			if ISBNlung>0:
				conn.execute('UPDATE `'+table+'` set `altrepagine`=\''+altrepagine+'\' WHERE (ISBN like CONVERT( _utf8 \''+keyISBN+'\'USING latin1 ) AND titolo like CONVERT( _utf8 \''+keytitolo+'\'USING latin1 )) LIMIT 1')
			else:
				conn.execute('UPDATE `'+table+'` set `altrepagine`=\''+altrepagine+'\' WHERE (titolo like CONVERT( _utf8 \''+keytitolo+'\'USING latin1 )) LIMIT 1')
			conn.close()
		else:
			return 0

def create_biblio():
	#We create the bibliography page. Please note that when we put some text we're always supposed to be at the beginning of a new line and that we must close every insertion with a \n char.
	conn=set_connection()#see above
	conn.execute('SELECT titolo,template,altrepagine from '+table+' where 1 ORDER BY `titolo` ASC') #take everything from the DB order by title
	rowcount=conn.rowcount	#This isn't really needed 
	conn.close()
	text='{{Progetto:fisica/Bibliointro}}\n== Indice ==\n' #We don't want to write everytime an introduction let's include a template
	iniziale=''
	for record in conn.fetchall():
		title=str(record[0].encode("utf-8")) #We are ordering by title
		title.capitalize() #Better to assure that the first letter is capitalized
		template=str(record[1].encode("utf-8")) #usual problem of encoding here
		other=str(record[2].encode("utf-8"))#and there plus we want strings not tuples
		newbook_1='*'+template+'\n*::<nowiki>'+template#Ok we are ready to prepare the wikitext for the entry. It's composed by the result of the template plus the template itself enclosed between nowiki tags (that's why we excluded the text enclosed in these tags from our search
		newbook_2='</nowiki>'#let's close the nowiki
		if len(other) > 0: #if we decided to take note of other copies of the template that should be regarded as important here we have to put a <ref>
			reflist=other.split('|') 
			reflist[0]=''#The first ref is the page in which the stored template was found.
			for ref in reflist:
				if ref==paginabibliografia: ref=''
				if ref==manualinsert: ref=''
				if len(ref) > 0:
					newbook_2=newbook_2+'<ref>Questo template potrebbe necessitare di essere manualmente integrato con i contenuti presenti nello stesso template apposto sulla pagina [['+ref+']]</ref>'#Maybe we should strip all the italian messages and be more international but we're going to wait to have requests
		newbook_3='\n'#Don't forget to change line
		newbook=newbook_1 + newbook_2 + newbook_3 #Ok here's the full entry
		if iniziale==title[0] : #Has the title the same first letter as the previous entry?
			text += newbook #ok let's add the new entry
		else:
			iniziale=title[0] #If not we are changing subsection
			newsection='=== '+iniziale+' ===\n' #here's the subsection's title
			text += newsection + newbook #here's the entry
	text+='== Note ==\n<references/>' #At the end as we inserted some notes it useful to have them displayed, isn't it?
	return text # Gave back the text to original function that would insert it in the correct page

def do_other_mant(page,text):
	#As we are looping we can take our time to perform some simple ops that are not handled by standard bots. Some "this project  only" tasks
	text=check_portal(page,text) #Here's the most obvious let's make sure that all the pages have the proper portal template
	return text #Give back the text to the original function. It knows (we hope) what to do with it

def check_portal(page,text):
	global pagemodified #This is needed in order to change the value of this variable in case we need to do this
	old= 'portale' #Search for portale
	pattern = '[' + re.escape(old[0].upper()) + re.escape(old[0].lower()) + ']' + re.escape(old[1:])
	templateRegex = re.compile(r'\{\{ *([Tt]emplate:|[mM][sS][gG]:)?' + pattern + r'(?P<parameters>\s*\|.+?|) *}}', re.DOTALL)
	match=re.search(templateRegex,text)
	if not match: #there's no portale in this page
		cat=page.categories() #are there any cats?
		interw=page.interwiki()#are there any interwikis?
		if len(cat) > 0: #we have at least one cat
			match_cat=re.search('\[\[Categoria:',text) #We have to put the template before the beginning of categories
			text=text[:match_cat.start()] + '\n{{portale|fisica}}\n\n' + match_cat.group() + text[match_cat.end():] #Insert the template and leave the rest alone
			pagemodified=True #eheheh :D
		elif len(interw) > 0 : #we have no cat bu we have at least one interwikis
			interwiki=wikipedia.getLanguageLinks(text) #let's retrive interwikis
			text=wikipedia.removeLanguageLinks(text) #let's remove them
			text += '\n\n{{portale|fisica}}\n\n'+wikipedia.interwikiFormat(interwiki) #and let's put them back after the template. W wikipedia.py embedded functions
			pagemodified=True
		else: #no cat no portal no interwikis ok this page was made by someone who doesn't really know what's doing. By the way this won't ever be called as we are looping over a cat. But anyway it's simple.
			text += '\n\n{{portale|fisica}}\n'
			pagemodified=True
	else: #we have a template already in (doesn't matter where)
		match_fisica=re.search('[Ff]isica',match.group()) #is fisica defined as parameter? Please note we're searching only in the portale code as we use match.group() as original text.
		if not match_fisica: #there's no fisica parameter. Who has stolen our page?
			nuovoportale=re.sub('}}','|fisica}}',match.group()) #Ok lets insert fisica as the last parameter. We take the }} template closing statement and we use it to insert the new parameter
			text=text[:match.start()] + nuovoportale + text[match.end():]# change only the portale and leave alone the remaining
			pagemodified=True
	return text #give back the text to the caller function. It'll handle it
	
def cercaparametro(temp,param,standard):
	#We have a template in input the name of a parameter and the standard parameters positions for that template in case the names (in case the template syntax allow for a positional filling). Are we ready to search?
	temp=re.sub('\n','',temp)#We don't want to have problems with \n
	plow=param.lower()#just in case someone wrote a capitalized param in lowercase
	pcap=param.capitalize()#or on the contrary if a lower was written capitalized
	match_param=re.search('\|\s*('+param+'|'+plow+'|'+pcap+')\s*=',temp)#search for anything similar to |  paramname  = with or without blanks
	if match_param: #we found it!
		match_end=re.search('(\||})',temp[match_param.end():])#let's search where it ends (it could end both with a new param (|) or with the end of temp (})
		value=temp[match_param.end():][:match_end.start()]#remember temp[match_param.end()] is a string itself and so we can attach another selector. Not mess with temp[match_param.end():match_end.start()] as match_end.start() was computed using only a substring of temp
		value=value.strip()#just in case of some blanks
		return value
	else:#:( no matches
		if param in standard: # but we can take a look if this template allows us to fill parameters simply using a positional syntax and if this parameter is to be found simply looking at its usual position
			position=standard[param]#here's the usual position
			temparray=temp.split('|')#we want to search for a specific position so we should have an array
			value=temparray[position]#ok let's hope. BTW the values in standard are defined starting from 1 so we can forgot about{{template name|
			match_equal=re.search('=',value)#Maybe we'have a template in which the parameter we are searching was simply omitted and we selected another parameter
			if match_equal: #If we are selecting a legitimate parameter then discard. Actually it could happen that a value of a position defined parameter itself contains and = sign... I still don't know how to handle this case
				return False #For now it's as not found
			else: 
				return value #ok we found a position defined parameter
		else:#it's not to be found by positional definition
			return False

def compilatemplate(name,keyarray,key_valuearray):
	#we are going to write down the template for wich we have a name, a set of keys, and a set of values
	text='{{'+name+''#start the wikitemplate
	for key in keyarray:#for every key...
		if key in key_valuearray:#...if it was used...
			if key_valuearray[key].strip()!='':#... and if its value isn't ill defined (i.e. simply blanks)...
				text+='|'+key+'='+key_valuearray[key]#.. take it and put into the template
	return text+'}}'


def set_connection():
	#we don't want to have too many place in which set the connection parameters, do we?
	global table
	conn = mysql_autoconnection.connect(retry_timeout = 5, max_retries = 4, host ='localhost', user = 'root', passwd = '', charset = 'utf8')
	conn.execute('USE test')
	table='librifisicawiki'
	return conn #just remember to give the connection handler back to the calling function or it won't work
	
if __name__ == '__main__':
    try:
        main()
    finally:
        wikipedia.stopme()

Codice per il progetto astronomia[modifica | modifica wikitesto]

Lo scopo è fare quanto più possibile di quello indicato in Discussioni utente:Roberto Mura/Sandbox2. Risultati di qualche prova in Discussioni utente:Roberto Mura/Sandbox3

 # coding=utf-8

import wikipedia # Import the wikipedia module
import pagegenerators
import re
import mysql_autoconnection
import sys
import httplib

def int_to_roman(input):
   if type(input) != type(1):
      raise TypeError, "expected integer, got %s" % type(input)
   if not 0 < input < 4000:
      raise ValueError, "Argument must be between 1 and 3999"   
   ints = (1000, 900,  500, 400, 100,  90, 50,  40, 10,  9,   5,  4,   1)
   nums = ('M',  'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
   result = ""
   for i in range(len(ints)):
      count = int(input / ints[i])
      result += nums[i] * count
      input -= ints[i] * count
   return result

def roman_to_int(input):
   if type(input) != type(""):
      raise TypeError, "expected string, got %s" % type(input)
   input = input.upper()
   nums = ['M', 'D', 'C', 'L', 'X', 'V', 'I']
   ints = [1000, 500, 100, 50,  10,  5,   1]
   places = []
   for c in input:
      if c not in nums:
         raise ValueError, "input is not a valid roman numeral: %s" % input
   for i in range(len(input)):
      value = ints[nums.index(input[i])]
      # If the next place holds a larger number, this value is negative.
      try:
         nextvalue = ints[nums.index(input[i +1])]
         if nextvalue > value:
            value *= -1
      except IndexError:
         # there is no next place.
         pass
      places.append(value)
   my_sum = sum(places)
   # Easiest test for validity...
   if int_to_roman(my_sum) == input:
      return my_sum
   else:
      raise ValueError, 'input is not a valid roman numeral: %s' % input

def main():
	dati_stella=ottieni_dati('HD+188753')
	text=prepara_testo(dati_stella,'HD 188753','Cnc','Pagina')
	wikipedia.output(text)


def ottieni_dati(nomestella):
	conn = httplib.HTTPConnection("simbad.u-strasbg.fr")
	linkname="/simbad/sim-basic?Ident="+nomestella+"&submit=SIMBAD+search?httpRadio=Get&output.format=ASCII_TAB&output.outline=on&output.max=10000&list.idsel=on&list.idopt=FIRST&list.idcat=&list.otypesel=on&otypedisp=3&list.coo1=on&frame1=ICRS&epoch1=2000&equi1=2000&coodisp1=s2&obj.coo2=on&list.coo2=on&frame2=FK5&epoch2=2000&equi2=2000&coodisp2=s2&obj.coo3=on&list.coo3=on&frame3=FK4&epoch3=1950&equi3=1950&coodisp3=s2&obj.coo4=on&list.coo4=on&frame4=Gal&epoch4=2000&equi4=2000&coodisp4=d2&obj.pmsel=on&list.pmsel=on&obj.plxsel=on&list.plxsel=on&obj.rvsel=on&list.rvsel=on&rvRedshift=on&rvRadvel=on&rvCZ=on&obj.fluxsel=on&list.fluxsel=on&U=on&B=on&V=on&R=on&I=on&obj.spsel=on&list.spsel=on&obj.mtsel=on&list.mtsel=on&obj.sizesel=on&list.sizesel=on&obj.bibsel=on&list.bibsel=on&bibyear1=1850&bibyear2=2008&bibjnls=&bibdisplay=bibnum&bibcom=on&obj.notesel=on&list.notesel=on&notedisplay=S&obj.messel=on&list.messel=on&list.mescat=&mesdisplay=A&obj.extsel=on&extVizier=on&extHeasarc=on&save=SAVE"
	conn.request("GET", linkname)
	r2 = conn.getresponse()
	print r2.status, r2.reason
	data2 = r2.read()
	conn.close()
	pattern_coordinate=r'Coordinates\(ICRS,ep=2000,eq=2000\):\s+(\d+)\s+(\d+)\s+(\d+\.?\d*)\s+([\+-])*(\d+)\s+(\d+)\s+(\d+\.?\d*)\s+'
	rex_coordinate=re.compile(pattern_coordinate)
	match_coordinate=re.search(rex_coordinate,data2)
	if not match_coordinate: return False
	coordinate_unite=match_coordinate.group().split(':')
	pattern_coordinate_2=r'\s+([\+-])*(\d+)\s+(\d+)\s+(\d+\.?\d*)'
	rex_coordinate_2=re.compile(pattern_coordinate_2)
	coordinate_divise_m=re.search(rex_coordinate_2,coordinate_unite[1].strip())
	dec_array=coordinate_divise_m.group().strip().split(' ')
	ra_array=coordinate_unite[1].strip()[:coordinate_divise_m.start()].strip().split(' ')
	
	pattern_coordinate_g=r'Coordinates\(Gal,ep=2000,eq=2000\):\s+(\d+\.?\d*)\s+([\+-])*(\d+\.?\d*)\s+'
	rex_coordinate_g=re.compile(pattern_coordinate_g)
	match_coordinate_g=re.search(rex_coordinate_g,data2)
	if not match_coordinate_g: return False
	coordinate_unite_g=match_coordinate_g.group().split(':')
	pattern_coordinate_2_g=r'\s+([\+-])*(\d+\.?\d*)'
	rex_coordinate_2_g=re.compile(pattern_coordinate_2_g)
	coordinate_divise_g_m=re.search(rex_coordinate_2_g,coordinate_unite_g[1].strip())
	lon_g=coordinate_divise_g_m.group().strip()
	lat_g=coordinate_unite_g[1].strip()[:coordinate_divise_g_m.start()].strip()
	
	pattern_moto=r'Proper motions:\s+([\+-])*(\d+\.?\d*)\s+([\+-])*(\d+\.?\d*)\s+'
	rex_moto=re.compile(pattern_moto)
	match_moto=re.search(rex_moto,data2)
	if not match_moto: return False
	moto_unite=match_moto.group().split(':')
	pattern_moto_2=r'\s+([\+-])*(\d+\.?\d*)'
	rex_moto_2=re.compile(pattern_moto_2)
	moto_divise_m=re.search(rex_moto_2,moto_unite[1].strip())
	dec=moto_divise_m.group().strip()
	ra=moto_unite[1].strip()[:moto_divise_m.start()].strip()
	
	pattern_vrad=r'Radial Velocity:\s+([\+-])*(\d+\.?\d*)\s+'
	rex_vrad=re.compile(pattern_vrad)
	match_vrad=re.search(rex_vrad,data2)
	if not match_vrad: return False
	vrad_unite=match_vrad.group().split(':')
	vrad=vrad_unite[1].strip()	
	
	pattern_para=r'Parallax:\s+([\+-])*(\d+\.?\d*)\s+'
	rex_para=re.compile(pattern_para)
	match_para=re.search(rex_para,data2)
	if not match_para: return False
	para_unite=match_para.group().split(':')
	para=para_unite[1].strip()
	
	pattern_fluxb=r'Flux B :\s+([\+-])*(\d+\.?\d*)\s+'
	rex_fluxb=re.compile(pattern_fluxb)
	match_fluxb=re.search(rex_fluxb,data2)
	if not match_fluxb: return False
	fluxb_unite=match_fluxb.group().split(':')
	fluxb=fluxb_unite[1].strip()
	
	pattern_fluxv=r'Flux V :\s+([\+-])*(\d+\.?\d*)\s+'
	rex_fluxv=re.compile(pattern_fluxv)
	match_fluxv=re.search(rex_fluxv,data2)
	if not match_fluxv: return False
	fluxv_unite=match_fluxv.group().split(':')
	fluxv=fluxv_unite[1].strip()
	
	pattern_classe=r'Spectral type:\s+[OBAFGKMW][\d.]*(0|Ib|Ia|II|III|IV|V|VI)[abc]*-*(0|Ib|Ia|II|III|IV|V|VI)*\s+'
	rex_classe=re.compile(pattern_classe)
	match_classe=re.search(rex_classe,data2)
	if not match_classe: return False
	classe_unite=match_classe.group().split(':')
	classe=classe_unite[1].strip()
	pattern_classe2='-+(0|Ib|Ia|II|III|IV|V|VI)+'
	rex_classe2=re.compile(pattern_classe2)
	match_classe2=re.search(rex_classe2,classe)
	classe2romano=' '
	if not match_classe2:
		pass
	else:
		classe2romano=match_classe2.group().strip('-')
		classe=classe[:match_classe2.start()]
	primaparte=re.search('[OBAFGKMW]',classe)
	numeroclasse=re.search('[\d.]+',classe)
	romano=re.search('(0|Ib|Ia|II|III|IV|V|VI)',classe)
	romanodef=' '
	if classe2romano!=' ' :
		if romano.group()=='Ib' : romanotry='I'
		elif romano.group()=='Ia' : romanotry='I'
		else : romanotry=romano.group()
		if classe2romano=='Ib' : romanotry2='I'
		elif classe2romano=='Ia' : romanotry2='I'
		else : romanotry2=classe2romano
		var1=roman_to_int(romanotry)
		var2=roman_to_int(romanotry2)
		if var1 > var2: romanodef=romano.group()
		elif var1 < var2: romanodef=classe2romano
		else: romanodef=romano.group()
	else:
		romanodef=romano.group()
	classef=primaparte.group()+' '+romanodef

	
	arrayincasinato=data2.split('\n\n')
	arraynote=arrayincasinato[-3]
	arraynotesplit=arraynote.split('\n')
	first_m='2'
	numero=0
	trovate=0
	nuovanota=False
	note={}
	for righenote in arraynotesplit:
		if first_m=='2':
			first_m='1'
		elif first_m=='1':
			numero_m=re.search(r'\(\d*\)',righenote)
			numero=int(numero_m.group().strip('()'))
			first_m='0'
		else:
			S_m=re.search('\(S\)',righenote)
			if S_m:
				trovate+=1
				nuovanota=True
			else:
				if nuovanota:
					note[trovate]=righenote
					nuovanota=False
				else:
					note[trovate]=note[trovate]+righenote
	if trovate!=numero:
		print('Problema con le note')
	numero_compagne='0'
	numero_pianeti='0'
	compagne={}
	pianeti={}
	for i in range(1, trovate+1):
		nota=note[i]
		compagna_m=re.search('component',nota)
		pianeta_m=re.search('planet',nota)
		if pianeta_m:
			arraydilavoro=nota.split('\object{')
			numero_pianeti=len(arraydilavoro)-1
			for j in range(1, numero_pianeti+1):
				questo_m=re.search('\**[\w\s]*}',arraydilavoro[j])
				pianeti[j]=questo_m.group().strip('*}')
		elif compagna_m:
			arraydilavoro1=nota.split('\object{')
			numero_compagne=len(arraydilavoro1)-1
			for j in range(1, numero_compagne+1):
				questo_m1=re.search('\**[\w\s\+\-]*}',arraydilavoro1[j])
				compagne[j]=questo_m1.group().strip('*}')


	Vrot=Ottieni_dato('ROT','Vsini',data2)
	Teff=Ottieni_dato('Fe_H','Teff',data2)
	Metal=Ottieni_dato('Fe_H','Fe_H',data2)
	dati={
	'RA':'{{RA|'+ra_array[0]+'|'+ra_array[1]+'|'+punto_to_virgola(ra_array[2])+'}}', 
	'DEC':'{{DEC|'+dec_array[0]+'|'+dec_array[1]+'|'+punto_to_virgola(dec_array[2])+'}}',
	'latg':punto_to_virgola(lat_g),
	'long':punto_to_virgola(lon_g),
	'Motoproprio':'{{Moto proprio|ar='+punto_to_virgola(ra)+'|dec='+punto_to_virgola(dec)+'}}',
	'Vradiale':punto_to_virgola(vrad),
	'parallasse':punto_to_virgola(para),
	'mb':punto_to_virgola(fluxb),
	'mv':punto_to_virgola(fluxv),
	'classe':classef,
	'classea':primaparte.group(),
	'classeab':numeroclasse.group(),
	'classeb':romanodef,
	'numero_pianeti':numero_pianeti,
	'numero_compagne':numero_compagne,
	'pianeti':pianeti,
	'compagne':compagne,
	'Vrot':punto_to_virgola(Vrot),
	'Teff':punto_to_virgola(Teff),
	'Metal':punto_to_virgola(Metal),
	'Link':linkname}
	return dati

def Ottieni_dato(catalogo,parametro,testo):
	match_catalogo=re.search('\s*'+catalogo+'\s*\|[^\n\r]+\n',testo)
	if not match_catalogo:
		return ' '
	else:
		match_parametri=re.search('\s*'+catalogo+'\s*\|[^\n\r]+\n',testo[match_catalogo.end():])
		if not match_parametri:
			print ord(testo[match_catalogo.end()])
			return ' '
		else:
			parametri=match_catalogo.group().split('|')
			i=0
			trovato=False
			for questo in parametri:
				if i==0:
					i+=1
				else:
					match_trova=re.search(parametro,questo.strip())
					if match_trova:
						trovato=True
						break
					else:
						i+=1
			if not trovato:
				return ' '
			else:
				valori=match_parametri.group().split('|')
				valore=valori[i]
				valore=valore.strip().split(' ')
				return valore[0]
				
def punto_to_virgola(testo):
	return re.sub('\.',',',testo)
				
def prepara_testo(dati_stella,nomestella,costellazione,startpage):
	tipo_stella={'O VI':'[[stella subnana|subnana]] blu',
	'B VI':'[[stella subnana|subnana]] azzurra',
	'A VI':'[[stella subnana|subnana]] bianca',
	'F VI':'[[stella subnana|subnana]] biancogialla',
	'G VI':'[[stella subnana|subnana]] gialla',
	'K VI':'[[stella subnana|subnana]] arancione',
	'M VI':'[[stella subnana|subnana]] rossa',
	'O V':'[[nana blu]] nella [[sequenza principale]]',
	'B V':'[[nana biancoazzurra]] nella [[sequenza principale]]',
	'A V':'[[stella bianca di sequenza principale|bianca]] nella [[sequenza principale]]',
	'F V':'[[nana biancogialla]] nella [[sequenza principale]]',
	'G V':'[[nana gialla]] nella [[sequenza principale]]',
	'K V':'[[nana arancione]] nella [[sequenza principale]]',
	'M V':'[[nana rossa]] nella [[sequenza principale]]',
	'O IV':'[[stella subgigante|subgigante]] blu',
	'B IV':'[[stella subgigante|subgigante]] azzurra',
	'A IV':'[[stella subgigante|subgigante]] bianca',
	'F IV':'[[stella subgigante|subgigante]] biancogialla',
	'G IV':'[[stella subgigante|subgigante]] gialla',
	'K IV':'[[stella subgigante|subgigante]] arancione',
	'M IV':'[[stella subgigante|subgigante]] rossa',
	'O III':'[[stella gigante|gigante]] [[gigante blu|blu]] nella [[sequenza principale]]',
	'B III':'[[stella gigante|gigante]] [[gigante blu|azzurra]] nella [[sequenza principale]]',
	'A III':'[[stella gigante|gigante]] bianca',
	'F III':'[[stella gigante|gigante]] biancogialla',
	'G III':'[[stella gigante|gigante]] gialla',
	'K III':'[[stella gigante|gigante]] [[gigante rossa|arancione]]',
	'M III':'[[stella gigante|gigante]] [[gigante rossa|rossa]]',
	'O II':'[[stella gigante brillante|gigante brillante]] [[gigante brillante blu|blu]] nella [[sequenza principale]]',
	'B II':'[[stella gigante brillante|gigante brillante]] [[gigante brillante blu|azzurra]] nella [[sequenza principale]]</nowiki>  Giganti brillanti blu]]',
	'A II':'[[stella gigante brillante|gigante brillante]] bianca',
	'F II':'[[stella gigante brillante|gigante brillante]] biancogialla',
	'G II':'[[stella gigante brillante|gigante brillante]] gialla',
	'K II':'[[stella gigante brillante|gigante brillante]] [[gigante brillante rossa|arancione]]',
	'M II':'[[stella gigante brillante|gigante brillante]] [[gigante brillante rossa|rossa]]',
	'O Ia':'[[stella supergigante|supergigante]] [[supergigante blu|blu]]',
	'B Ia':'[[stella supergigante|supergigante]] [[supergigante blu|azzurra]]',
	'A Ia':'[[stella supergigante|supergigante]] bianca',
	'F Ia':'[[stella supergigante|supergigante]] [[supergigante gialla|biancogialla]]',
	'G Ia':'[[stella supergigante|supergigante]] [[supergigante gialla|gialla]]',
	'K Ia':'[[stella supergigante|supergigante]] [[supergigante rossa|arancione]]',
	'M Ia':'[[stella supergigante|supergigante]] [[supergigante rossa|rossa]]',
	'O Ib':'[[stella supergigante|supergigante]] [[supergigante blu|blu]]',
	'B Ib':'[[stella supergigante|supergigante]] [[supergigante blu|azzurra]]',
	'A Ib':'[[stella supergigante|supergigante]] bianca',
	'F Ib':'[[stella supergigante|supergigante]] [[supergigante gialla|biancogialla]]',
	'G Ib':'[[stella supergigante|supergigante]] [[supergigante gialla|gialla]]',
	'K Ib':'[[stella supergigante|supergigante]] [[supergigante rossa|arancione]]',
	'M Ib':'[[stella supergigante|supergigante]] [[supergigante rossa|rossa]]',
	'O 0':'[[stella ipergigante|ipergigante]] blu',
	'B 0':'[[stella ipergigante|ipergigante]] azzurra',
	'A 0':'[[stella ipergigante|ipergigante]] bianca',
	'F 0':'[[stella ipergigante|ipergigante]] biancogialla',
	'G 0':'[[stella ipergigante|ipergigante]] [[ipergigante gialla|gialla]]',
	'K 0':'[[stella ipergigante|ipergigante]] arancione',
	'M 0':'[[stella ipergigante|ipergigante]] rossa',
	'W':'[[stella di WolfRayet|di WolfRayet]], blu'}
	
	categoria_stella={'O VI':'[[Categoria:Subnane blu]]',
	'B VI':'[[Categoria:Subnane blu]]',
	'A VI':'[[Categoria:Subnane blu]]',
	'F VI':'[[Categoria:Subnane gialle]]',
	'G VI':'[[Categoria:Subnane gialle]]',
	'K VI':'[[Categoria:Subnane rosse]]',
	'M VI':'[[Categoria:Subnane rosse]]',
	'O V':'[[Categoria:Nane blu]]',
	'B V':'[[Categoria:Nane biancoazzurre]]',
	'A V':'[[Categoria:Nane biancoazzurre]]',
	'F V':'[[Categoria:Nane biancogialle]]',
	'G V':'[[Categoria:Nane gialle]]',
	'K V':'[[Categoria:Nane arancioni]]',
	'M V':'[[Categoria:Nane rosse]]',
	'O IV':'[[Categoria:Subgiganti blu]]',
	'B IV':'[[Categoria:Subgiganti blu]]',
	'A IV':'[[Categoria:Subgiganti bianche]]',
	'F IV':'[[Categoria:Subgiganti gialle]]',
	'G IV':'[[Categoria:Subgiganti gialle]]',
	'K IV':'[[Categoria:Subgiganti rosse]]',
	'M IV':'[[Categoria:Subgiganti rosse]]',
	'O III':'[[Categoria:Giganti blu]]',
	'B III':'[[Categoria:Giganti blu]]',
	'A III':'[[Categoria:Giganti bianche]]',
	'F III':'[[Categoria:Giganti gialle]]',
	'G III':'[[Categoria:Giganti gialle]]',
	'K III':'[[Categoria:Giganti rosse]]',
	'M III':'[[Categoria:Giganti rosse]]',
	'O II':'[[Categoria:Giganti brillanti blu]]',
	'B II':'[[Categoria:Giganti brillanti blu]]',
	'A II':'[[Categoria:Giganti brillanti blu]]',
	'F II':'[[Categoria:Giganti brillanti gialle]]',
	'G II':'[[Categoria:Giganti brillanti gialle]]',
	'K II':'[[Categoria:Giganti brillanti rosse]]',
	'M II':'[[Categoria:Giganti brillanti rosse]]',
	'O Ia':'[[Categoria:Supergiganti blu]]',
	'B Ia':'[[Categoria:Supergiganti blu]]',
	'A Ia':'[[Categoria:Supergiganti bianche]]',
	'F Ia':'[[Categoria:Supergiganti gialle]]',
	'G Ia':'[[Categoria:Supergiganti gialle]]',
	'K Ia':'[[Categoria:Supergiganti rosse]]',
	'M Ia':'[[Categoria:Supergiganti rosse]]',
	'O Ib':'[[Categoria:Supergiganti blu]]',
	'B Ib':'[[Categoria:Supergiganti blu]]',
	'A Ib':'[[Categoria:Supergiganti bianche]]',
	'F Ib':'[[Categoria:Supergiganti gialle]]',
	'G Ib':'[[Categoria:Supergiganti gialle]]',
	'K Ib':'[[Categoria:Supergiganti rosse]]',
	'M Ib':'[[Categoria:Supergiganti rosse]]',
	'O 0':'[[Categoria:Ipergiganti blu]]',
	'B 0':'[[Categoria:Ipergiganti blu]]',
	'A 0':'[[Categoria:Ipergiganti blu]]',
	'F 0':'[[Categoria:Ipergiganti gialle]]',
	'G 0':'[[Categoria:Ipergiganti gialle]]',
	'K 0':'[[Categoria:Ipergiganti rosse]]',
	'M 0':'[[Categoria:Ipergiganti rosse]]',
	'W':' '}
	
	link_costellazioni={'Aqr':'dell\'[[Aquario (costellazione)|Aquario]]',
	'Ara':'dell\'[[Altare (costellazione)|Altare]]',
	'And':'di [[Andromeda (costellazione)|Andromeda]]',
	'Aql':'dell\'[[Aquila (costellazione)|Aquila]]',
	'Ari':'dell\'[[Ariete (costellazione)|Ariete]]',
	'Aur':'dell\'[[Auriga (costellazione)|Auriga]]',
	'Cet':'della [[Balena (costellazione)|Balena]]',
	'Lib':'della [[Bilancia (costellazione)|Bilancia]]',
	'Boo':'del [[Boote (costellazione)|Boote]]',
	'Cae':'del [[Bulino (costellazione)|Bulino]]',
	'Pyx':'della [[Bussola (costellazione)|Bussola]]',
	'Cha':'del [[Camaleonte (costellazione)|Camaleonte]]',
	'Cnc':'del [[Cancro (costellazione)|Cancro]]',
	'CMa':'dei [[Cani da Caccia (costellazione)|Cani da Caccia]]',
	'CMi':'del [[Cane Maggiore (costellazione)|Cane Maggiore]]',
	'CVn':'del [[Cane Minore (costellazione)|Cane Minore]]',
	'Cap':'del [[Capricorno (costellazione)|Capricorno]]',
	'Car':'della [[Carena (costellazione)|Carena]]',
	'Cas':'di [[Cassiopea (costellazione)|Cassiopea]]',
	'Equ':'del [[Cavallino (costellazione)|Cavallino]]',
	'Cep':'del [[Centauro (costellazione)|Centauro]]',
	'Cen':'di [[Cefeo (costellazione)|Cefeo]]',
	'Com':'della [[Chioma di Berenice (costellazione)|Chioma di Berenice]]',
	'Cyg':'del [[Cigno (costellazione)|Cigno]]',
	'Col':'della [[Colomba (costellazione)|Colomba]]',
	'Cir':'del [[Compasso (costellazione)|Compasso]]',
	'CrA':'della [[Corona Australe (costellazione)|Corona Australe]]',
	'CrB':'dela [[Corona Boreale (costellazione)|Corona Boreale]]',
	'Crv':'del [[Corvo (costellazione)|Corvo]]',
	'Crt':'del [[Cratere (costellazione)|Cratere]]',
	'Cru':'della [[Croce del Sud (costellazione)|Croce del Sud]]',
	'Del':'del [[Delfino (costellazione)|Delfino]]',
	'Dor':'del [[Dorado (costellazione)|Dorado]]',
	'Dra':'del [[Dragone (costellazione)|Dragone]]',
	'Her':'di [[Ercole (costellazione)|Ercole]]',
	'Eri':'dell\'[[Eridano (costellazione)|Eridano]]',
	'Phe':'della [[Fenice (costellazione)|Fenice]]',
	'For':'della [[Fornace (costellazione)|Fornace]]',
	'Sge':'della [[Freccia (costellazione)|Freccia]]',
	'Gem':'dei [[Gemelli (costellazione)|Gemelli]]',
	'Cam':'della [[Giraffa (costellazione)|Giraffa]]',
	'Gru':'della [[Gru (costellazione)|Gru]]',
	'Hya':'dell\'[[Idra (costellazione)|Idra]]',
	'Hyi':'dell\'[[Idra Maschio (costellazione)|Idra Maschio]]',
	'Ind':'dell\'[[Indiano (costellazione)|Indiano]]',
	'Leo':'della [[Lucertola (costellazione)|Lucertola]]',
	'LMi':'del [[Leone (costellazione)|Leone]]',
	'Lep':'del [[Leone Minore (costellazione)|Leone Minore]]',
	'Lyn':'della [[Lepre (costellazione)|Lepre]]',
	'Lyr':'della [[Lince (costellazione)|Lince]]',
	'Lac':'della [[Lira (costellazione)|Lira]]',
	'Lup':'del [[Lupo (costellazione)|Lupo]]',
	'Ant':'della [[Macchina Pneumatica (costellazione)|Macchina Pneumatica]]',
	'Men':'della [[Mensa (costellazione)|Mensa]]',
	'Mic':'del [[Microscopio (costellazione)|Microscopio]]',
	'Mus':'della [[Mosca (costellazione)|Mosca]]',
	'Oph':'dell\'[[Ofiuco (costellazione)|Ofiuco]]',
	'Ori':'di [[Orione (costellazione)|Orione]]',
	'Hor':'dell\'[[Orologio (costellazione)|Orologio]]',
	'UMa':'dell\'[[Orsa Maggiore (costellazione)|Orsa Maggiore]]',
	'UMi':'dell\'[[Orsa Minore (costellazione)|Orsa Minore]]',
	'Oct':'dell\'[[Ottante (costellazione)|Ottante]]',
	'Pav':'del [[Pavone (costellazione)|Pavone]]',
	'Peg':'di [[Pegaso (costellazione)|Pegaso]]',
	'Per':'di [[Perseo (costellazione)|Perseo]]',
	'PsA':'del [[Pesce Australe (costellazione)|Pesce Australe]]',
	'Vol':'del [[Pesce Volante (costellazione)|Pesce Volante]]',
	'Psc':'dei [[Pesci (costellazione)|Pesci]]',
	'Pic':'del [[Pittore (costellazione)|Pittore]]',
	'Pup':'della [[Poppa (costellazione)|Poppa]]',
	'Nor':'Del [[ Regolo (costellazione)|Regolo]]',
	'Ret':'del [[Reticolo (costellazione)|Reticolo]]',
	'Sgr':'del [[Sagittario (costellazione)|Sagittario]]',
	'Sco':'dello [[Scorpione (costellazione)|Scorpione]]',
	'Sct':'dello [[Scudo (costellazione)|Scudo]]',
	'Scl':'dello [[Scultore (costellazione)|Scultore]]',
	'Ser':'del [[Serpente (costellazione)|Serpente]]',
	'Sex':'del [[Sestante (costellazione)|Sestante]]',
	'Tel':'del [[Telescopio (costellazione)|Telescopio]]',
	'Tau':'del [[Toro (costellazione)|Toro]]',
	'Tri':'del [[Triangolo (costellazione)|Triangolo]]',
	'TrA':'del [[Triangolo Australe (costellazione)|Triangolo Australe]]',
	'Tuc':'del [[Tucano (costellazione)|Tucano]]',
	'Aps':'dell\'[[Uccello del Paradiso (costellazione)|Uccello del Paradiso]]',
	'Mon':'dell\'[[Unicorno (costellazione)|Unicorno]]',
	'Vel':'delle [[Vele (costellazione)|Vele]]',
	'Vir':'della [[Vergine (costellazione)|Vergine]]',
	'Vul':'della [[Volpetta (costellazione)|Volpetta]]'}
	
	sigle_costellazioni={'Aqr':'Acquario',
	'Ara':'Altare',
	'And':'Andromeda',
	'Aql':'Aquila',
	'Ari':'Ariete',
	'Aur':'Auriga',
	'Cet':'Balena',
	'Lib':'Bilancia',
	'Boo':'Boote',
	'Cae':'Bulino',
	'Pyx':'Bussola',
	'Cha':'Camaleonte',
	'Cnc':'Cancro',
	'CMa':'CaneMaggiore',
	'CMi':'CaneMinore',
	'CVn':'CanidaCaccia',
	'Cap':'Capricorno',
	'Car':'Carena',
	'Cas':'Cassiopea',
	'Equ':'Cavallino',
	'Cep':'Cefeo',
	'Cen':'Centauro',
	'Com':'ChiomadiBerenice',
	'Cyg':'Cigno',
	'Col':'Colomba',
	'Cir':'Compasso',
	'CrA':'CoronaAustrale',
	'CrB':'CoronaBoreale',
	'Crv':'Corvo',
	'Crt':'Cratere',
	'Cru':'CrocedelSud',
	'Del':'Delfino',
	'Dor':'Dorado',
	'Dra':'Dragone',
	'Her':'Ercole',
	'Eri':'Eridano',
	'Phe':'Fenice',
	'For':'Fornace',
	'Sge':'Freccia',
	'Gem':'Gemelli',
	'Cam':'Giraffa',
	'Gru':'Gru',
	'Hya':'Idra',
	'Hyi':'IdraMaschio',
	'Ind':'Indiano',
	'Leo':'Leone',
	'LMi':'LeoneMinore',
	'Lep':'Lepre',
	'Lyn':'Lince',
	'Lyr':'Lira',
	'Lac':'Lucertola',
	'Lup':'Lupo',
	'Ant':'MacchinaPneumatica',
	'Men':'Mensa',
	'Mic':'Microscopio',
	'Mus':'Mosca',
	'Oph':'Ofiuco',
	'Ori':'Orione',
	'Hor':'Orologio',
	'UMa':'OrsaMaggiore',
	'UMi':'OrsaMinore',
	'Oct':'Ottante',
	'Pav':'Pavone',
	'Peg':'Pegaso',
	'Per':'Perseo',
	'PsA':'PesceAustrale',
	'Vol':'PesceVolante',
	'Psc':'Pesci',
	'Pic':'Pittore',
	'Pup':'Poppa',
	'Nor':'Regolo',
	'Ret':'Reticolo',
	'Sgr':'Sagittario',
	'Sco':'Scorpione',
	'Sct':'Scudo',
	'Scl':'Scultore',
	'Ser':'Serpente',
	'Sex':'Sestante',
	'Tel':'Telescopio',
	'Tau':'Toro',
	'Tri':'Triangolo',
	'TrA':'TriangoloAustrale',
	'Tuc':'Tucano',
	'Aps':'UccellodelParadiso',
	'Mon':'Unicorno',
	'Vel':'Vele',
	'Vir':'Vergine',
	'Vul':'Volpetta'}
	lettera={1:'b',
	2:'c',
	3:'d',
	4:'e',
	5:'f',
	6:'g',
	7:'h',
	8:'i'}
	
	greche=['alpha',
	'beta',
	'gamma',
	'delta',
	'epsilon',
	'zeta',
	'eta',
	'theta',
	'iota',
	'kappa',
	'lambda',
	'mu',
	'nu',
	'xi',
	'omicron',
	'pi',
	'rho',
	'sigma',
	'tau',
	'upsilon',
	'phi',
	'chi',
	'psi',
	'omega']
	
	greca=' '	
	pezzistella=nomestella.strip().split(' ')
	if pezzistella[0].lower() in greche:
		greca='([[nomenclatura di Bayer|&'+pezzistella[0].lower()+'; Cancri/ &'+pezzistella[0].lower()+'; Cnc]]) '

	
	text='{{corpo celeste\n|tipo=Stella\n|nome_stella='+nomestella+'\n|sigla_costellazione='+costellazione+'\n|categoria='+categoria_stella[dati_stella['classe']]+'\n|ar='+dati_stella['RA']+'\n|declinaz='+dati_stella['DEC']+'\n|epoca=J2000|lat_galattica='+dati_stella['latg']+'\n|long_galattica='+dati_stella['long']+'\n|classe_spettrale='+dati_stella['classea']+dati_stella['classeab']+dati_stella['classeb']+'	\n|designazioni_alternative_stellari=\n|redshift=\n|diametro_med=\n|raggio_sole=\n|schiacciamento=\n|massa=\n|massa_sole=\n|densità=\n|periodo_rotaz=\n|velocità_rotaz='
	if dati_stella['Vrot']!=' ':
		text+=dati_stella['Vrot']+' km/s'
	text+='\n|velocità_rotaz_note=\n|inclinazione_asse_su_piano_galattico=\n|temp_min=\n|temp_med='
	if dati_stella['Teff']!=' ':
		text+=dati_stella['Teff']+' K'
	text+='\n|temp_max=\n|temp_corona=\n|temp_nucleo=\n|luminosità=\n|luminosità_sole=\n|radianza=\n|indice_di_colore=|metallicità='
	if dati_stella['Metal']!=' ':
		text+=dati_stella['Metal']+' %'
	text+='\n|età=\n|magn_app='+dati_stella['mv']+'([[magnitudine visuale|m<sub>v</sub>]]) - '+dati_stella['mb']+'([[magnitudine blu|m<sub>b</sub>]])\n|magn_ass=\n|parallasse='+dati_stella['parallasse']+'\n|moto_proprio='+dati_stella['Motoproprio']+'\n|velocità_radiale=\n|}}\n\n'

	if len(dati_stella['compagne']) == 0:
		text+='\'\'\' '+nomestella+'\'\'\' '+greca+'è una [[stella]] '+tipo_stella[dati_stella['classe']]+' visibile nella [[costellazione]] '+link_costellazioni[costellazione]+'.\n\n'
	else:
		if len(dati_stella['compagne'])==1: quante='doppio'
		elif len(dati_stella['compagne'])==2: quante='triplo'
		elif len(dati_stella['compagne'])==3: quante='quadruplo'
		else: quante='multiplo'
		text+='\'\'\' '+nomestella+'\'\'\' '+greca+'è un [[sistema stellare]] '+quante+' visibile nella [[costellazione]] '+link_costellazioni[costellazione]+'.\n\nLa componente principale A è una '+tipo_stella[dati_stella['classe']]+'.\n\n'
		if len(dati_stella['compagne'])==1: text+='La sua compagna è: '
		else: text+='Le sue compagne sono: '
		for i in range(len(dati_stella['compagne'])):
			if i+1 < len(dati_stella['compagne']):
				text+='[['+dati_stella['compagne'][i+1]+']], '
			else: text+='[['+dati_stella['compagne'][i+1]+']].'
		text+='\n\n'
	if dati_stella['numero_pianeti']!='0':
		text+="Si ritiene che attorno alla stella orbitino almeno "+str(dati_stella['numero_pianeti'])+" pianeti ("
		for i in range(len(dati_stella['pianeti'])):
			if i+1 < len(dati_stella['pianeti']):
				text+='[['+nomestella+' '+lettera[i+1]+']], '
			else: text+='[['+nomestella+' '+lettera[i+1]+']]'
		text+=').\n\n'
	text+="==Voci correlate==\n*[["+startpage+"]]\n\n==Collegamenti esterni==\n*[http://simbad.u-strasbg.fr"+dati_stella['Link']+" SIMBAD query result]\n\n{{Portale|stelle}}\n\n[[Categoria:Stelle di classe spettrale "+dati_stella['classea']+"]]\n"+categoria_stella[dati_stella['classe']]+"\n\n"
	return text
	
	
if __name__ == '__main__':
    try:
        main()
    finally:
        wikipedia.stopme()