On Nov 28, 9:00 am, "Joseph king" <[EMAIL PROTECTED]> wrote: > Hey i was wondering if any one would know if there was a way to have > python randomly read form a file or would you ahve to know the byte > postion and somehow randomize splicing the file so the sentence you > want show's up. > > i.e have a file with a lot of tips and useless facts and then have > python randomly read one sentence when the code is run and print at > any time you would want it to.
Python can handle it just fine. You probably want to create a text file with a standard delimiter between quotes, perhaps a text line with three to five equal signs ('==='). Open the file object [1], read in all the data [2], split the data into a list by the delimiter [3], then choose a random string from the list [4]. For example: >>> import random >>> quotes = open('quotes.txt').read() >>> quoteList = quotes.split('===\n') >>> print random.choice( quoteList ) This is a single sentence that repels vikings. >>> print random.choice( quoteList ) This is a single sentence that repels vikings. >>> print random.choice( quoteList ) This is a crazy, multi-line quote! It's so very, very crazy! -Personal Attribution >>> Obviously, you might need to deal with leading and trailing whitespace [5]. If you are restricted to a series of paragraphs in the text file, you'll need to split the string at the sentence separating punctuation. There's a lot of ways that punctuation can work in English, so splitting on periods, exclamation points, and question marks may not work if you have elipses (...) in the document. You'll probably need to split using a regular expression [6]. If you are reading a formatted file of some sort (such as XML, HTML, badly-formatted HTML, Word documents, PDFs, etc), you'll need to figure out how to read the document in Python. While Python has XML support and some HTML support [7], you'll probably want Beautiful Soup [8] to read badly formatted HTML. Word documents are much trickier, and it's usually easiest to use Microsoft Word to save to a plain text format. Hope this helps you out! --Jason [1] http://docs.python.org/lib/built-in-funcs.html [2] http://docs.python.org/lib/bltin-file-objects.html [3] http://docs.python.org/lib/string-methods.html [4] http://docs.python.org/lib/module-random.html [5] http://docs.python.org/lib/string-methods.html [6] http://docs.python.org/lib/node46.html [7] http://docs.python.org/lib/markup.html [8] http://www.crummy.com/software/BeautifulSoup/ -- http://mail.python.org/mailman/listinfo/python-list