Re: [Tutor] [Python-Help] Please help replace Long place-names with short place-names in many files with Python
Welcome. We are a few volunteers who like to help you when you have tried something and are stuck. It is best to post to just one email list. Most of us monitor tutor and help. We don't write programs for you. Some of us would be happy to do that for a consulting fee. Why Python? What other programming experience do you have? Do you know the basics: getting a list of filenames in a directory? loops? opening and reading / writing files? searching for strings in larger strings? replacing strings? OMG I just wrote the outline of your program! Try writing a program to do some of the above then come back with questions. Start with something simple - process just one file. Or hire me as a consultant and I will write it for you. [snip] -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Please help replace Long place-names with short place-names in many files with Python
Dear Pythonistas, I am totally new to Python. This means a know the basics. And by basics I mean the very, very basics. I have a problem with which I need help. in short, I need to: a) Open many files (in a dir) with an .html extension b) Find Long name-places (Austria) c) Replace them by short name.places (AT) d) In the context of the xml tags ( and ) At length: I have many xml files containing a day of speeches at the European Parliament each file. Each file has some xml-label for the session metadata and then the speakers (MPs) interventions. These interventions consist of my metadata and text. I include here a sample of two speeches (Please pay attention to xml labels and ): SAMPLE OF INTERVENTIONS Knapman, Roger 19440220 Crediton NA male UK Independence Party on behalf of the group Mr President, Mr Juncker's speech was made with all the passion that a civil servant is likely to raise. Mr Juncker, you say that the Stability and Growth Pact will be your top priority, but your past statements serve to illustrate only the inconsistencies. Whilst I acknowledge that you played a key role in negotiating the pact's original rules, you recently said that the credibility of the pact had been buried and that the pact was dead. Is that still your opinion? You also said that you have a window of opportunity to cut a quick deal on the EU budget, including the British rebate of some EUR 4 billion a year. Is that so, Mr Juncker? The rebate took five years to negotiate. If your comments are true and you can cut a deal by June, then Mr Blair must have agreed in principle to surrender the rebate. Is that the case? With whom in the British Government precisely are you negotiating? Will the British electorate know about this at the time of the British general election, probably in May? Finally, the UK Independence Party, and in particular my colleague Mr Farage, has drawn attention to the criminal activities of more than one Commissioner. More details will follow shortly and regularly. Are you to be tainted by association with them, or will you be expressing your concerns and the pressing need for change? Angelilli, Roberta 19650201 Roma NA female Alleanza nazionale on behalf of the group Mr President, the Luxembourg Presidency’s programme is packed with crucial issues for the future of Europe, including the priorities on the economic front: the Lisbon strategy, reform of the Stability Pact and approval of the financial perspective up to 2013. My first point is that it will soon be time for the mid-term review of the level of implementation of the Lisbon strategy. To give it a greater chance of success, the programme needs to make the individual Member States responsible for achieving the targets that were set. To that end, I consider the proposal to specify an individual at national level to be responsible for putting the strategy into practice to be a very useful idea. Secondly, with regard to the review of the Stability Pact, it has also been emphasised this morning that a reform is needed which can propose a more flexible interpretation of the Pact during times of recession, without bypassing the Maastricht criteria and without giving up the commitment to reduce the debt. I am also convinced that steps could be taken to exclude certain specific types of investment from the calculation of the deficit in order to give a new boost to Europe’s growth and competitiveness. Thirdly, I hope that we can really succeed in approving the financial perspective up to 2013 by June, so that the resources can be used to the full from the very beginning of the period in question. I especially hope that the proposals – the Council’s and the Commission’s proposals on those important topics – are adequately discussed in advance by Parliament which, let us recall, is the only European institution that directly represents the sovereignty of the people. Lastly, I hope that a European civil protection agency will at last be set up during the Luxembourg Presidency so that natural disasters can be dealt with in an appropriate manner, with particular emphasis on prevention. END OF SAMPLE OF INTERVENTIONS * Now, as you see, label: and Have long place-names. For instance and But I would like short place-names (UK instead of United Kingdom, for instance) The long-names I have are all the members of the European Union. LIST OF LONG PLACE-NAMES AND EQUIVALENT SHORT PLACE-NAMES Austria = AT Belgium = BE Bulgaria = BG Croatia = HR Cyprus = CY Czech Republic = CS Denmark = DK Estonia = EE Finland = FI France = FR Germany = DE Greece = GR Hungary = HU Ireland = IE Italy = IT Latv
Re: [Tutor] Tutor Digest, Vol 115, Issue 2
help On Sun, Sep 1, 2013 at 12:00 PM, wrote: > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-requ...@python.org > > You can reach the person managing the list at > tutor-ow...@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > >1. Re: myown.getfilesystemencoding() (eryksun) > > > -- > > Message: 1 > Date: Sun, 1 Sep 2013 01:30:21 -0400 > From: eryksun > To: Oscar Benjamin , Albert-Jan Roskam > > Cc: Python Mailing List > Subject: Re: [Tutor] myown.getfilesystemencoding() > Message-ID: > < > cacl+1asfy+so2bt3ubndp7vjtkhmumilmdekf9njtmjkjhk...@mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > On Sat, Aug 31, 2013 at 9:16 AM, Oscar Benjamin > wrote: > > Spyder has both an internal interpreter and an external interpreter. > > One is the same interpreter process that runs the Spyder GUI. The > > other is run in a subprocess which keeps the GUI safe but reduces your > > ability to inspect the workspace data via the GUI. So presumable > > Albert means the "external" interpreter here. > > I installed Spyder on Windows to look into this. It's using Qt > QProcess to run the external interpreter in a child process. > sys.stdin.isatty() confirms it's not a tty, and Process Explorer > confirms that all 3 standard I/O handles (from msvcrt.get_osfhandle()) > are pipes. > > The file encoding is None for piped standard I/O, so printing unicode > falls back to the default encoding. Normally this is ASCII in 2.x, but > Spyder uses sitecustomize to set the default encoding based on the > default locale. It also sets the hidden console's codepage: > > if os.name == 'nt': # Windows platforms > > # Setting console encoding (otherwise Python does not > # recognize encoding) > try: > import locale, ctypes > _t, _cp = locale.getdefaultlocale('LANG') > try: > _cp = int(_cp[2:]) > ctypes.windll.kernel32.SetConsoleCP(_cp) > ctypes.windll.kernel32.SetConsoleOutputCP(_cp) > except (ValueError, TypeError): > # Code page number in locale is not valid > pass > except ImportError: > pass > > http://code.google.com/p/spyderlib/source/browse/spyderlib/ > widgets/externalshell/sitecustomize.py?name=v2.2.0#74 > > Probably this was added for a good reason, but I don't grok the point. > Python isn't interested in the hidden console window at this stage, > and the standard handles are all pipes. I didn't notice any difference > with these lines commented out, running with Python 2.7.5. YMMV > > There's a design flaw here since sys.stdin.encoding is used by the > parser in single-input mode. With it set to None, Unicode literals > entered in the REPL will be incorrectly parsed if they use non-ASCII > byte values. For example, given the input is Windows 1252, then u'?' > will be parsed as u'\x80' (i.e. PAD, a C1 Control code). > > Here's an alternative to messing with the default encoding -- at least > for the new version of Spyder that doesn't have to support 2.5. Python > 2.6+ checks for the PYTHONIOENCODING environment variable. This > overrides the encoding/errors values in Py_InitializeEx(): > > http://hg.python.org/cpython/file/70274d53c1dd/Python/pythonrun.c#l265 > > You can test setting PYTHONIOENCODING without restarting Spyder. Just > bring up Spyder's "Internal Console" and set > os.environ['PYTHONIOENCODING']. The change applies to new interpreters > started from the "Interpreters" menu. Spyder could set this itself in > the environment that gets passed to the QProcess object. > > > -- > > Subject: Digest Footer > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- > > End of Tutor Digest, Vol 115, Issue 2 > * > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] input loop
Hi, I am trying to create a portfolio of shares, each share is entered manually while checking it against a list of actual share codes.Its working mostly as intended at the moment, except when I print the table out at the end, I want all entered details printed as such Enter command: addEnter share code to add: tpwTPW = TrustPowerEnter share price: 2Enter share quantity: 5Enter command: print--Code Price Quant Value--TPW 2.00 5 10.00--Total cost: 10.00== **(This is all even when displayed in Wing101) So thats all fine, but I'm wanting muiltiple more rows printed underneath with other shares and their prices etc. Getting stuck on that, I know i'll need a for loop to iterate over the input but still wanting to get some help. here's the rest of the code so far. PROMPT_FOR_COMMAND = 'Enter command: 'PROMPT_FOR_CODE = 'Enter share code to add: 'PROMPT_FOR_PRICE = 'Enter share price: 'PROMPT_FOR_QUANTITY = 'Enter share quantity: ' MESSAGE_UNKNOWN_COMMAND ='Unknown command - please try again.'MESSAGE_UNKNOWN_CODE = 'Unknown code - CANCELLING code entry.'MESSAGE_PORTFOLIO_EMPTY = 'No shares in portfolio.'MESSAGE_GOODBYE = 'Thankyou and goodbye.' TITLE_TEMPLATE = '{:<6}{:>8}{:>8}{:>12}'LINE_ITEM_TEMPLATE = '{:<6}{:>8.2f}{:>8}{:>12.2f}'LINE_TOTAL_TEMPLATE = '{:<20}{:>14.2f}'SPACER_LINE = 34 * '-'DBL_SPACE_LINE = 34 * "=" def print_portfolio_table(portfolio):""" Prints out a portfolio table as per specification.You can use the test_print_portfolio_table to test this function..."""print(SPACER_LINE)print(TITLE_TEMPLATE.format("Code", "Price", "Quant", "Value"))print(SPACER_LINE) print(LINE_ITEM_TEMPLATE.format(code, price, quant, (price * quant))) print(SPACER_LINE)print(LINE_TOTAL_TEMPLATE.format("Total cost:", (price * quant)))print(DBL_SPACE_LINE) def process_add_code(portfolio):"""Receives a portfolio list.Asks for a share code.If it's in the exchange then prints code = fullnamethen gets price and quantity from the userthen it appends the (code, price, quantity) to the portfolio"""global codecode = input(PROMPT_FOR_CODE).upper() if shares.in_exchange(code) == True:print(code + " " + "=" + " " + shares.get_name(code))global priceprice = float(input(PROMPT_FOR_PRICE))global quantquant = int(input(PROMPT_FOR_QUANTITY))portfolio = portfolio.append([code, price, quant])main()else:print(MESSAGE_UNKNOWN_CODE) main() def main():"""This is the main function for the program, ie, this function is called first when the program is run"""# The portfolio list will contain tuples as (code, price, quantity)# Initially it is empty portfolio = []command = input(PROMPT_FOR_COMMAND).lower()if command == 'add':return portfolio.append(process_add_code(portfolio))if command == "print" and len(portfolio) <= 1: print_portfolio_table(portfolio)return main()if command == "quit": print(MESSAGE_GOODBYE) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] input loop
On 1/9/2013 17:53, Nick Wilson wrote: > Hi, Welcome. Please start over with a text message. Your html email is useless to me, and probably most people on this newsgroup. 5 10.00--Total cost: 10.00==**(This is all even when displayed in Wing101)So thats all fine, but I'm wanting muiltiple more rows printed underneath with other shares and their prices etc. Getting stuck on that, I know i'll need a for loop to iterate over the input but still wanting to get some help.here's the rest of the code so far.PROMPT_FOR_COMMAND = 'Enter command: 'PROMPT_FOR_CODE = 'Enter share code to add: 'PROMPT_FOR_PRICE = 'Enter share price: -- DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Please help replace Long place-names with short place-names in many files with Python
On Sun, Sep 1, 2013 at 4:19 PM, mc UJI wrote: > Dear Pythonistas, > > I am totally new to Python. This means a know the basics. And by basics I > mean the very, very basics. > > I have a problem with which I need help. > > in short, I need to: > > a) Open many files (in a dir) with an .html extension Do you know how to do this? Its not hard. Google 'python reading all files in a directory' to get started > b) Find Long name-places (Austria) > c) Replace them by short name.places (AT) In python strings are objects and they have the replace method (look here: http://docs.python.org/2/library/string.html#string.replace) If you figure out how to read each file into a string (see above), you just run the string.replace method on it for each long-short country pair. Then write the file. Try first to write this code. If you apply yourself, it will take you maybe an hour to get something working. Then come back with your code and tell us what went wrong. > d) In the context of the xml tags ( and > ) > > At length: > > I have many xml files containing a day of speeches at the European > Parliament each file. Each file has some xml-label for the session metadata > and then the speakers (MPs) interventions. These interventions consist of my > metadata and text. I include here a sample of two speeches (Please pay > attention to xml labels and country=".*?"/> ): > > >SAMPLE OF INTERVENTIONS > > > Knapman, Roger > 19440220 > Crediton > NA > male > > > > > > > > UK Independence Party > > > on behalf of the group > > > Mr President, Mr Juncker's speech was made with > all the passion that a civil servant is likely to raise. > Mr Juncker, you say that the Stability and > Growth Pact will be your top priority, but your past statements serve to > illustrate only the inconsistencies. Whilst I acknowledge > that you played a key role in negotiating the pact's original rules, you > recently said that the credibility of the pact had been buried and that the > pact was dead. Is that still your opinion? > You also said that you have a window of > opportunity to cut a quick deal on the EU budget, including the British > rebate of some EUR 4 billion a year. Is that so, Mr > Juncker? The rebate took five years to > negotiate. If your comments are true and you can cut a > deal by June, then Mr Blair must have agreed in principle to surrender the > rebate. Is that the case? With whom in > the British Government precisely are you negotiating? Will > the British electorate know about this at the time of the British general > election, probably in May? > Finally, the UK Independence Party, and in > particular my colleague Mr Farage, has drawn attention to the criminal > activities of more than one Commissioner. More details > will follow shortly and regularly. Are you to be tainted > by association with them, or will you be expressing your concerns and the > pressing need for change? > > > > > > Angelilli, Roberta > 19650201 > Roma > NA > female > > > > > > > > Alleanza nazionale > > > on behalf of the group > > > Mr President, the Luxembourg Presidency’s > programme is packed with crucial issues for the future of Europe, including > the priorities on the economic front: the Lisbon strategy, reform of the > Stability Pact and approval of the financial perspective up to 2013. > My first point is that it will soon be time for > the mid-term review of the level of implementation of the Lisbon > strategy. To give it a greater chance of success, the > programme needs to make the individual Member States responsible for > achieving the targets that were set. To that end, I > consider the proposal to specify an individual at national level to be > responsible for putting the strategy into practice to be a very useful > idea. > Secondly, with regard to the review of the > Stability Pact, it has also been emphasised this morning that a reform is > needed which can propose a more flexible interpretation of the Pact during > times of recession, without bypassing the Maastricht criteria and without > giving up the commitment to reduce the debt. I am also > convinced that steps could be taken to exclude certain specific types of > investment from the calculation of the deficit in order to give a new boost > to Europe’s growth and competitiveness. > Thirdly, I hope that we can really succeed in > approving the financial perspective up to 2013 by June, so that the > resources can be used to the full from the very beginning of the period in > question. I especially hope that the proposals – the > Council’s and the Commission’s proposals on those important topics – are > adequately discussed in advance by Parliament which, let us recall, is the > only European institution that directly represents the sovereignty of the > people. > Lastly, I hope that a European civil protection > agenc
Re: [Tutor] input loop
On 01/09/13 22:53, Nick Wilson wrote: Enter command: print -- Code Price Quant Value -- The bit above needs to be printed once, at the start TPW 2.00 5 10.00 This bit needs to be repeated for each share type -- Total cost: 10.00 == And this bit needs to be printed once at the end after doing the calculations. **(This is all even when displayed in Wing101) That will depend on fonts used etc. If you really need it aligned neatly I recommend using html and displaying it in a browser, but its a lot more work that way! PROMPT_FOR_COMMAND = 'Enter command: ' PROMPT_FOR_CODE = 'Enter share code to add: ' PROMPT_FOR_PRICE = 'Enter share price: ' PROMPT_FOR_QUANTITY = 'Enter share quantity: ' Were you ever a COBOL programmer by any chance? def main(): """This is the main function for the program, ie, this function is called first when the program is run""" There is nothing in Python that will run this first. You need to call it explicitly. This is often done inside a name test clause: if __name__ == "__main__": main() command = input(PROMPT_FOR_COMMAND).lower() if command == 'add': return portfolio.append(process_add_code(portfolio)) Are you sure you want to return here? That will terminate the main function without saving portfolio. You may want to create a menu system where you repeatedly ask for input until quit is selected. if command == "print" and len(portfolio) <= 1: print_portfolio_table(portfolio) return main() if command == "quit": print(MESSAGE_GOODBYE) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor