Главная » Просмотр файлов » Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007

Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889), страница 13

Файл №779889 Wiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (Symbian Books) 13 страницаWiley.Mobile.Python.Rapid.prototyping.of.applications.on.the.mobile.platform.Dec.2007 (779889) страница 132018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 13)

The following codeoutputs the string ‘fancy message’:a = " fancy message "print a.strip()This is actually one of the most often needed operations for strings – inthis book it is used in 12 examples. It is especially useful when youreceive data from a file or over a network connection.You can replace a substring in a string with the function replace().The following example outputs ‘Python is the future’:a = "Java is the future"print a.replace("Java", "Python")You can also replace individual characters in a string, which is oftenuseful for cleaning up input, say, from a web service. The followingexample removes all spaces in a string and outputs ‘1,2,3,4,5,6’.STRING HANDLING63a = " 1, 2, 3, 4, 5,6 "print a.replace(" ", "")If you need to cut a string into a list of substrings, use the functionsplit().

In default mode, split() cuts the string at every spacecharacter. If you give a string parameter to split(), it is used as thedelimiter instead. The following example prints out the list ["one","two", "three", "four"].txt = "one:two:three:four"print txt.split(":")4.3.5Formatting OutputThe real workhorse of Python’s string handling is the string-templatingmechanism. It is used to assemble a string based on other variables, whichcan be integers, floating-point numbers or other strings. To insert givenvalues in the middle of a string, you need to use special placeholders thatstart with the character ‘%’.The placeholders are replaced with variable values which are givenin a tuple. The template string and the corresponding input tuple arecombined with a percent sign operator, as shown below.The placeholders must agree with the variable types, so if your variablecontains an integer, you must use placeholder ‘%d’.

If your variable isanother string, the corresponding placeholder should be ‘%s’. A comprehensive list of possible placeholders and their modifiers can be found inthe Python documentation.Here is an example:printprintans =print"There are only %d lines in my code" % (5)"Hello %s of %d" % ("world", 2007)[45, 32, 12]"the correct answers are %d, %d, and %d" % tuple(ans)You should guess the output. Note that on the last line the input isgiven as a list which is converted to a tuple by the function tuple()before it is used to fill in the placeholders.You can use the ‘%d’ placeholder to convert an integer to a string. Toconvert a string to the corresponding integer, use function int().

Forexample, int("12") produces integer 12, but int("a12") fails sincethe input contains an invalid value.ExerciseTo get some practice with the string operations, let’s consider the followingscenario. There is a song contest running on television and the audiencecan vote for their favorite song and singer by SMS.64APPLICATION BUILDING AND SMS INBOXThere are four songs which you are interested in: 1, 3, 9 and 11.The competition is such that each song can be sung by any singer.

Yourfavorite singers are Tori, Kate and Alanis. To maximize the probabilitythat any of your favorite singers will get to perform at least one of thesongs, you decide to vote for all the singer–song combinations. Sinceyou realize that writing 12 text messages of format ‘VOTE [song] [singer]’manually is too much work, you quickly code the script in Example 13to do the job.Example 13: SMS voterimport messagingPHONE_NUMBER = "+10987654321"songs = (1, 3, 9, 11)singers = "Tori, Kate, Alanis"for song in songs:for singer in singers.split(","):msg = u"VOTE %d %s" % (song, singer.strip())print "Sending SMS", msgmessaging.sms_send(PHONE_NUMBER, msg)Here, the songs of interest are stored in the songs tuple.

Your favoritesingers are given in the comma-separated string singers. Since wewant to go through every possible singer–song combination, we firststart looping through all songs and for each song we loop through allsingers.However, we need to convert the singers string to a list for looping,so we splice the string using the split() function. The split()function produces the list ["Tori", " Kate", " Alanis"]. Note thatthe names of Kate and Alanis are preceded by an unnecessary space.We use the function strip() to get rid of leading white space.Finally we construct a voting message with a template string.

Since thesong identifiers are integers, they require the %d placeholder. Likewise,the string placeholder %s is used for the names.Be careful with the combination of loops and the sms send()function, such as the one above. In real life, each SMS message costsmoney and with loops you can easily send thousands of them! You mightwant to try out this example without a SIM card in your phone, just to beon the safe side.4.4 SMS InboxEven though a large number of today’s mobile phones support variousInternet protocols, from VoIP and instant messaging to HTTP, only SMSSMS INBOX65can guarantee smooth interoperability between all devices, includingold models.

It is reasonable to assume that every mobile phone userknows how to send and receive SMS messages. Because of this, SMSmessages are still widely used to interact with various services, frombuying bus tickets to television shows and online dating. Let your imagination free and come up with novel ways to use these services withPython!You have already seen how to send SMS messages with the smssend() function. In addition, PyS60 provides the Inbox object, part ofthe inbox module, that can be used to access messages in your phone’sSMS inbox.

The latest versions of PyS60 may include access to other SMSfolders as well, such as the outbox for sent messages.You can also define a callback function that is called when a newmessage is received. This powerful feature enables you to build SMSservices of your own, or you can turn your phone into an SMS gatewaythat forwards received messages to a new phone number.4.4.1 Accessing the SMS InboxLet’s start with an example which shows five messages from your SMSinbox.Example 14: SMS inboximport inbox, appuifwbox = inbox.Inbox()for sms_id in box.sms_messages()[:5]:msg = box.content(sms_id)appuifw.note(msg)Besides the familiar appuifw module, which is needed for showingnotes, we need to import the inbox module that encapsulates access tothe SMS inbox.All functions related to receiving SMS messages belong to the Inboxobject which is created with the inbox.Inbox() function.

To read anindividual SMS message, you need to know its message ID.The Inbox object’s function sms messages() returns message IDsfor all messages in your phone’s SMS inbox. Since you may be a textingmaniac who keeps thousands of messages in the inbox, this exampleshows up to five of them. From the list returned by the sms messages()function, we slice off the first five items using the slicing operator [:5].The content() function returns the content of a message given itsmessage ID.

The content, or the actual text of the message, is then shownin a popup note.66APPLICATION BUILDING AND SMS INBOX4.4.2 SMS SearchExample 15 is a useful script: a search tool for your SMS inbox. Firstthe script asks for some text for which to search. Then it goes throughyour SMS inbox and shows excerpts of messages which contain the givenstring. You can see the full message by selecting a desired list item.Example 15: Inbox searchimport inbox, appuifwbox = inbox.Inbox()query = appuifw.query(u"Search for:", "text").lower()hits = []ids = []for sms_id in box.sms_messages():msg = box.content(sms_id).lower()if msg.find(query) != -1:hits.append(msg[:25])ids.append(sms_id)index = appuifw.selection_list(hits, 1)if index >= 0:appuifw.note(box.content(ids[index]))First, the string for which to search is stored in the variable query.

Asin the previous example, we use the sms messages() function of theInbox object to retrieve a list of all message IDs.The program loops through all messages, retrieves the contents of eachmessage with the content() function and tries to find the query stringin each message. If the find() function reports that the query stringoccurs in the message, we add the message ID to the list ids so that itcan be found later. Also, we add an excerpt (the first 25 characters) of themessage contents to the list hits, so that we can present this match tothe user.When we have processed all messages, we show the hits in a selectionlist using the message excerpts as list items.

When the user chooses anitem, the list dialog returns the item’s index in the list. Using this index,we find the corresponding message ID in the ids list and the full messagecontent can be fetched from the phone’s SMS inbox and shown to theuser.4.4.3 SMS SorterBesides the message content, it is possible to fetch the timestamp, thesender’s phone number (address) and information on whether the messagehas been read already using the Inbox object.To show how to use these functions, we make an application thatincludes an Exit key handler, an application title and a menu.

ThisSMS INBOX67application can be used to sort your SMS inbox according to various attributes of text messages. You can choose, using the applicationmenu, whether the messages should be sorted by time, sender or unreadflag.Example 16: Inbox sorterimport inbox, appuifw, e32def show_list(msgs):msgs.sort()items = []for msg in msgs:items.append(msg[1][:15])appuifw.selection_list(items)def sort_time():msgs = []for sms_id in box.sms_messages():msgs.append((-box.time(sms_id), box.content(sms_id)))show_list(msgs)def sort_sender():msgs = []for sms_id in box.sms_messages():msgs.append((box.address(sms_id), box.content(sms_id)))show_list(msgs)def sort_unread():msgs = []for sms_id in box.sms_messages():msgs.append((-box.unread(sms_id), box.content(sms_id)))show_list(msgs)def quit():print "INBOX SORTER EXITS"app_lock.signal()box = inbox.Inbox()appuifw.app.exit_key_handler = quitappuifw.app.title = u"Inbox Sorter"appuifw.app.menu = [(u"Sort by time", sort_time),(u"Sort by sender", sort_sender),(u"Unread first", sort_unread)]print "INBOX SORTER STARTED"app_lock = e32.Ao_lock()app_lock.wait()The code may seem long but notice that the functions sort time(),sort sender() and sort unread() are almost identical.

Характеристики

Тип файла
PDF-файл
Размер
3,61 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6447
Авторов
на СтудИзбе
306
Средний доход
с одного платного файла
Обучение Подробнее