itextsharp pdf to image c# : Create a fillable pdf form from a pdf application Library tool html asp.net azure online book_00712-part1807

Chapter9
Dictionaries
Adictionaryislikealist,butmoregeneral.Inalist,thepositions(a.k.a.indices)
havetobeintegers;inadictionarytheindicescanbe(almost)anytype.
Youcanthinkofadictionaryasamappingbetweenasetofindices(whichare
calledkeys)andasetofvalues. Eachkeymapstoavalue. Theassociationofa
keyandavalueiscalledakey-valuepairorsometimesanitem.
Asanexample,we’llbuildadictionarythatmapsfromEnglishtoSpanishwords,
sothekeysandthevaluesareallstrings.
Thefunction
dict
createsanewdictionarywithnoitems. Because
dict
isthe
nameofabuilt-infunction,youshouldavoidusingitasavariablename.
>>> eng2sp = dict()
>>> print eng2sp
{}
Thesquiggly-brackets,
{}
,representanemptydictionary. Toadditemstothe
dictionary,youcanusesquarebrackets:
>>> eng2sp[
'
one
'
] =
'
uno
'
Thislinecreatesanitemthatmapsfromthekey
’one’
tothevalue'
uno
'.Ifwe
printthedictionaryagain,weseeakey-valuepairwithacolonbetweenthekey
andvalue:
>>> print eng2sp
{
'
one
'
:
'
uno
'
}
Thisoutputformatisalsoaninputformat. Forexample,youcancreateanew
dictionarywiththreeitems:
>>> eng2sp = {
'
one
'
:
'
uno
'
,
'
two
'
:
'
dos
'
,
'
three
'
:
'
tres
'
}
Butifyouprint
eng2sp
,youmightbesurprised:
Create a fillable pdf form from a pdf - C# PDF Field Edit Library: insert, delete, update pdf form field in C#.net, ASP.NET, MVC, Ajax, WPF
Online C# Tutorial to Insert, Delete and Update Fields in PDF Document
change font pdf fillable form; create a form in pdf
Create a fillable pdf form from a pdf - VB.NET PDF Field Edit library: insert, delete, update pdf form field in vb.net, ASP.NET, MVC, Ajax, WPF
How to Insert, Delete and Update Fields in PDF Document with VB.NET Demo Code
create a pdf form; changing font in pdf form
108
Chapter9. Dictionaries
>>> print eng2sp
{
'
one
'
:
'
uno
'
,
'
three
'
:
'
tres
'
,
'
two
'
:
'
dos
'
}
Theorderofthekey-valuepairsisnotthesame. Infact,ifyoutypethesame
exampleonyourcomputer,youmightgetadifferentresult.Ingeneral,theorder
ofitemsinadictionaryisunpredictable.
Butthat’snotaproblembecausetheelementsofadictionaryareneverindexed
withintegerindices.Instead,youusethekeystolookupthecorrespondingvalues:
>>> print eng2sp[
'
two
'
]
'
dos
'
Thekey
’two’
alwaysmapstothevalue'
dos
'sotheorderoftheitemsdoesn’t
matter.
Ifthekeyisn’tinthedictionary,yougetanexception:
>>> print eng2sp[
'
four
'
]
KeyError:
'
four
'
The
len
functionworksondictionaries;itreturnsthenumberofkey-valuepairs:
>>> len(eng2sp)
3
The
in
operatorworksondictionaries;ittellsyouwhethersomethingappearsas
akeyinthedictionary(appearingasavalueisnotgoodenough).
>>>
'
one
'
in eng2sp
True
>>>
'
uno
'
in eng2sp
False
Toseewhethersomethingappearsas avalueinadictionary, youcanusethe
method
values
,whichreturnsthevaluesasalist,andthenusethe
in
operator:
>>> vals = eng2sp.values()
>>>
'
uno
'
in vals
True
The
in
operatorusesdifferentalgorithmsforlistsanddictionaries. Forlists,it
usesalinearsearchalgorithm.Asthelistgetslonger,thesearchtimegetslonger
indirectproportiontothe lengthofthelist. . Fordictionaries, , Pythonuses an
algorithmcalledahashtablethathas aremarkableproperty; ; the
in
operator
takesaboutthesameamountoftimenomatterhowmanyitemsthereareina
dictionary. Iwon’texplainwhyhashfunctionsaresomagical,butyoucanread
moreaboutitat
wikipedia.org/wiki/Hash_table
.
Exercise9.1 Writeafunctionthatreadsthewordsin
words.txt
andstoresthem
askeysinadictionary. Itdoesn’tmatterwhatthevaluesare. Thenyoucanuse
the
in
operatorasafastwaytocheckwhetherastringisinthedictionary.
C# Create PDF Library SDK to convert PDF from other file formats
Create fillable PDF document with fields. Load PDF from existing documents and image in SQL server. Load PDF from stream programmatically.
change font size pdf fillable form; change font size pdf form reader
VB.NET Create PDF from OpenOffice to convert odt, odp files to PDF
Edit Bookmark. Metadata: Edit, Delete Metadata. Form Process. Create PDF document from OpenOffice Text Document with ODT, ODS, ODP forms into fillable PDF formats
create a fillable pdf form in word; pdf form maker
9.1. Dictionaryasasetofcounters
109
9.1 Dictionaryasasetofcounters
Supposeyouaregivenastringandyouwanttocounthowmanytimeseachletter
appears.Thereareseveralwaysyoucoulddoit:
1. Youcouldcreate26variables,oneforeachletterofthealphabet.Thenyou
couldtraversethestringand,foreachcharacter,incrementthecorrespond-
ingcounter,probablyusingachainedconditional.
2. Youcouldcreatealistwith26elements. . Thenyoucouldconverteach
charactertoanumber(usingthebuilt-infunction
ord
),usethenumberas
anindexintothelist,andincrementtheappropriatecounter.
3. Youcouldcreateadictionarywithcharactersaskeysandcountersasthe
correspondingvalues. Thefirsttimeyouseeacharacter,youwouldadd
anitemtothedictionary. Afterthatyouwouldincrementthevalueofan
existingitem.
Eachoftheseoptionsperformsthesamecomputation,buteachofthemimple-
mentsthatcomputationinadifferentway.
Animplementationisawayofperformingacomputation;someimplementations
arebetterthanothers.Forexample,anadvantageofthedictionaryimplementation
isthatwedon’thavetoknowaheadoftimewhichlettersappearinthestringand
weonlyhavetomakeroomforthelettersthatdoappear.
Hereiswhatthecodemightlooklike:
def histogram(s):
d = = dict()
for c in s:
if c not t in n d:
d[c] = = 1
else:
d[c] = = d[c] + + 1
return d
Thenameofthefunctionishistogram, whichisastatisticaltermforasetof
counters(orfrequencies).
Thefirstlineofthefunctioncreatesanemptydictionary.The
for
looptraverses
thestring. Eachtimethroughtheloop,ifthecharacter
c
isnotinthedictionary,
wecreateanewitemwithkey
c
andtheinitialvalue1(sincewehaveseenthis
letteronce).If
c
isalreadyinthedictionaryweincrement
d[c]
.
Here’showitworks:
>>> h h = = histogram(
'
brontosaurus
'
)
>>> print h
{
'
a
'
: 1,
'
b
'
: 1,
'
o
'
: 2,
'
n
'
: 1,
'
s
'
: 2,
'
r
'
: 2,
'
u
'
: 2,
'
t
'
: 1}
C# Create PDF from OpenOffice to convert odt, odp files to PDF in
Create PDF document from OpenOffice Presentation in both .NET WinForms and ASP.NET NET control to change ODT, ODS, ODP forms to fillable PDF formats in Visual
change font on pdf form; can save pdf form data
VB.NET Create PDF Library SDK to convert PDF from other file
Create fillable PDF document with fields in Visual Basic .NET application. Load PDF from existing documents and image in SQL server.
pdf form save; chrome save pdf with fields
110
Chapter9. Dictionaries
Thehistogramindicatesthattheletters
’a’
and'
b
'appearonce;'
o
'appears
twice,andsoon.
Exercise9.2 Dictionarieshaveamethodcalled
get
thattakesakeyandadefault
value. Ifthekeyappearsinthedictionary,
get
returnsthecorrespondingvalue;
otherwiseitreturnsthedefaultvalue.Forexample:
>>> h h = = histogram(
'
a
'
)
>>> print h
{
'
a
'
: 1}
>>> h.get(
'
a
'
, 0)
1
>>> h.get(
'
b
'
, 0)
0
Use
get
towrite
histogram
moreconcisely.Youshouldbeabletoeliminatethe
if
statement.
9.2 Dictionariesandfiles
Oneofthecommonusesofadictionaryistocounttheoccurrenceofwordsin
afilewithsomewrittentext. Let’sstartwithaverysimplefileofwordstaken
fromthetextofRomeoandJulietthanksto
http://shakespeare.mit.edu/
Tragedy/romeoandjuliet/romeo_juliet.2.2.html
.
Forthefirstsetofexamples,wewilluseashortenedandsimplifiedversionof
thetextwithnopunctuation. Laterwewillworkwiththetextofthescenewith
punctuationincluded.
But soft what light through yonder window breaks
It is s the e east and Juliet t is s the sun
Arise fair r sun and kill the envious moon
Who is s already y sick and pale with grief
WewillwriteaPythonprogramtoreadthroughthelinesofthefile,breakeach
lineintoalistofwords,andthenloopthrougheachofthewordsintheline,and
counteachwordusingadictionary.
Youwillseethatwehavetwo
for
loops. Theouterloopisreadingthelinesof
thefileandtheinnerloopisiteratingthrougheachofthewordsonthatparticular
line.Thisisanexampleofapatterncallednestedloopsbecauseoneoftheloops
istheouterloopandtheotherloopistheinnerloop.
Becausetheinnerloopexecutesallofitsiterationseachtimetheouterloopmakes
asingleiteration,wethinkoftheinnerloopasiterating“morequickly”andthe
outerloopasiteratingmoreslowly.
Thecombinationofthetwonestedloopsensuresthatwewillcounteveryword
oneverylineoftheinputfile.
VB.NET Create PDF from PowerPoint Library to convert pptx, ppt to
Convert multiple pages PowerPoint to fillable and editable PDF documents. Easy to create searchable and scanned PDF files from PowerPoint.
create a fillable pdf form from a pdf; add attachment to pdf form
VB.NET Create PDF from Word Library to convert docx, doc to PDF in
formatting. Create PDF files from both DOC and DOCX formats. Convert multiple pages Word to fillable and editable PDF documents. Professional
change text size pdf form; changing font size in a pdf form
9.3. Loopinganddictionaries
111
fname = = raw_input(
'
Enter the e file name:
'
)
try:
fhand = open(fname)
except:
print
'
File cannot t be e opened:
'
, fname
exit()
counts = = dict()
for line in fhand:
words = line.split()
for word in n words:
if word d not t in counts:
counts[word] = = 1
else:
counts[word] += 1
print counts
Whenweruntheprogram,weseearawdumpofallofthecountsinunsortedhash
order.(the
romeo.txt
fileisavailableat
www.py4inf.com/code/romeo.txt
)
python count1.py
Enter the e file name: romeo.txt
{
'
and
'
: 3,
'
envious
'
: 1,
'
already
'
: 1,
'
fair
'
: 1,
'
is
'
: 3,
'
through
'
: 1,
'
pale
'
: 1,
'
yonder
'
: 1,
'
what
'
: 1,
'
sun
'
: 2,
'
Who
'
: 1,
'
But
'
: 1,
'
moon
'
: 1,
'
window
'
: 1,
'
sick
'
: 1,
'
east
'
: 1,
'
breaks
'
: 1,
'
grief
'
: 1,
'
with
'
: 1,
'
light
'
: 1,
'
It
'
: 1,
'
Arise
'
: 1,
'
kill
'
: 1,
'
the
'
: 3,
'
soft
'
: 1,
'
Juliet
'
: 1}
Itisabitinconvenienttolookthroughthedictionarytofindthemostcommon
wordsandtheircounts,soweneedtoaddsomemorePythoncodetogetusthe
outputthatwillbemorehelpful.
9.3 Loopinganddictionaries
Ifyouuseadictionaryasthesequenceina
for
statement,ittraversesthekeysof
thedictionary. Forexample,
print_hist
printseachkeyandthecorresponding
value:
def print_hist(h):
for c in h:
print c, , h[c]
Here’swhattheoutputlookslike:
>>> h h = = histogram(
'
parrot
'
)
>>> print_hist(h)
a 1
p 1
r 2
t 1
o 1
VB.NET Create PDF from Excel Library to convert xlsx, xls to PDF
Link: Edit URL. Bookmark: Edit Bookmark. Metadata: Edit, Delete Metadata. Form Process. Create fillable and editable PDF documents from Excel in Visual
add image field to pdf form; adding form fields to pdf files
C# Create PDF from Excel Library to convert xlsx, xls to PDF in C#
Create fillable and editable PDF documents from Excel in both .NET WinForms and ASP.NET. Create searchable and scanned PDF files from Excel.
adding text fields to pdf acrobat; adding a signature to a pdf form
112
Chapter9. Dictionaries
Again,thekeysareinnoparticularorder.
Ifyouwanttoprintthekeysinalphabeticalorder,youfirstmakealistofthekeys
inthedictionaryusingthe
keys
methodavailableindictionaryobjects,andthen
sortthatlistandloopthroughthesortedlist, lookingupeachkeyprintingout
key/valuepairsinsortedorderasfollowsasfollows:
def print_sorted_hist(h):
lst = h.keys()
lst.sort()
for c in lst:
print c, , h[c]
Here’swhattheoutputlookslike:
>>> h h = = histogram(
'
parrot
'
)
>>> print_sorted_hist(h)
a 1
o 1
p 1
r 2
t 1
Sonowthekeysareinalphabeticalorder.
9.4 Advancedtextparsing
Intheaboveexampleusingthefile
romeo.txt
,wemadethefileassimpleas
possiblebyremovinganyandallpunctuationbyhand. Therealtexthaslotsof
punctuationasshownbelow:
But, soft! what t light t through yonder r window w breaks?
It is s the e east, , and d Juliet t is s the sun.
Arise, fair r sun, , and d kill l the e envious s moon,
Who is s already y sick and pale with grief,
SincethePython
split
functionlooksforspacesandtreatswordsastokenssep-
aratedbyspaces,wewouldtreatthewords“soft!” and“soft”asdifferentwords
andcreateaseparatedictionaryentryforeachword.
Alsosincethefilehascapitalization,wewouldtreat“who”and“Who”asdifferent
wordswithdifferentcounts.
We can solve both these problems by using the e string g methods
lower
,
punctuation
,and
translate
.The
translate
isthemostsubtleofthemethods.
Hereisthedocumentationfor
translate
:
string.translate(s, table[, deletechars])
Deleteallcharactersfromsthatareindeletechars(ifpresent),andthentranslate
thecharactersusingtable,whichmustbea256-characterstringgivingthetrans-
lationforeachcharactervalue,indexedbyitsordinal.IftableisNone,thenonly
thecharacterdeletionstepisperformed.
C# Create PDF from PowerPoint Library to convert pptx, ppt to PDF
Convert multiple pages PowerPoint to fillable and editable PDF documents. Easy to create searchable and scanned PDF files from PowerPoint.
pdf form creator; add email button to pdf form
9.4. Advancedtextparsing
113
Wewillnotspecifythe
table
butwewillusethe
deletechars
parameterto
deleteallofthepunctuation.WewillevenletPythontellusthelistofcharacters
thatitconsiders“punctuation”:
>>> import string
>>> string.punctuation
'
!"#$%&\
'
()*+,-./:;<=>?@[\\]ˆ_
`
{|}˜
'
Wemakethefollowingmodificationstoourprogram:
import string
# New w Code
fname = = raw_input(
'
Enter the e file name:
'
)
try:
fhand = open(fname)
except:
print
'
File cannot t be e opened:
'
, fname
exit()
counts = = dict()
for line in fhand:
line = line.translate(None, string.punctuation)
# New w Code
line = line.lower()
# New w Code
words = line.split()
for word in n words:
if word d not t in counts:
counts[word] = = 1
else:
counts[word] += 1
print counts
Weuse
translate
toremoveallpunctuationand
lower
toforcethelinetolow-
ercase. Otherwisetheprogramisunchanged. . NoteforPython2.5andearlier,
translate
doesnotaccept
None
asthefirstparametersousethiscodeforthe
translatecall:
print a.translate(string.maketrans(
' '
,
' '
), string.punctuation
Partoflearningthe“ArtofPython”or“ThinkingPythonically”isrealizingthat
Pythonoftenhasbuilt-incapabilitiesformanycommondata-analysisproblems.
Overtime,youwillseeenoughexamplecodeandreadenoughofthedocumenta-
tiontoknowwheretolooktoseeifsomeonehasalreadywrittensomethingthat
makesyourjobmucheasier.
Thefollowingisanabbreviatedversionoftheoutput:
Enter the e file name: romeo-full.txt
{
'
swearst
'
: 1,
'
all
'
: 6,
'
afeard
'
: 1,
'
leave
'
: 2,
'
these
'
: 2,
'
kinsmen
'
: 2,
'
what
'
: 11,
'
thinkst
'
: 1,
'
love
'
: 24,
'
cloak
'
: 1,
a
'
: 24,
'
orchard
'
: 2,
'
light
'
: 5,
'
lovers
'
: 2,
'
romeo
'
: 40,
'
maiden
'
: 1,
'
whiteupturned
'
: 1,
'
juliet
'
: 32,
'
gentleman
'
: 1,
'
it
'
: 22,
'
leans
'
: 1,
'
canst
'
: 1,
'
having
'
: 1, ...}
114
Chapter9. Dictionaries
LookingthroughthisoutputisstillunwieldyandwecanusePythontogivesus
exactlywhatwearelookingfor, buttodoso, weneedtolearnaboutPython
tuples.Wewillpickupthisexampleoncewelearnabouttuples.
9.5 Debugging
Asyouworkwithbiggerdatasetsitcanbecomeunwieldytodebugbyprintingand
checkingdatabyhand.Herearesomesuggestionsfordebugginglargedatasets:
Scaledowntheinput: Ifpossible,reducethesizeofthedataset.Forexampleif
theprogramreadsatextfile,startwithjustthefirst10lines,orwiththe
smallestexampleyoucanfind. Youcaneithereditthefilesthemselves,or
(better)modifytheprogramsoitreadsonlythefirst
n
lines.
Ifthereisanerror,youcanreduce
n
tothesmallestvaluethatmanifeststhe
error,andthenincreaseitgraduallyasyoufindandcorrecterrors.
Checksummariesandtypes: Insteadofprintingandcheckingtheentiredataset,
considerprintingsummariesofthedata:forexample,thenumberofitems
inadictionaryorthetotalofalistofnumbers.
Acommoncauseofruntimeerrorsisavaluethatisnottherighttype.For
debuggingthiskindoferror,itisoftenenoughtoprintthetypeofavalue.
Writeself-checks: Sometimesyoucanwritecodetocheckforerrorsautomati-
cally. Forexample,ifyouarecomputingtheaverageofalistofnumbers,
youcouldcheckthattheresultisnotgreaterthanthelargestelementin
thelistorlessthanthesmallest. Thisiscalleda“sanitycheck”becauseit
detectsresultsthatare“insane.”
Anotherkindofcheckcomparestheresultsoftwodifferentcomputations
toseeiftheyareconsistent.Thisiscalleda“consistencycheck.”
Prettyprinttheoutput: Formattingdebuggingoutputcanmakeiteasiertospot
anerror.
Again,timeyouspendbuildingscaffoldingcanreducethetimeyouspenddebug-
ging.
9.6 Glossary
dictionary: Amappingfromasetofkeystotheircorrespondingvalues.
hashtable: ThealgorithmusedtoimplementPythondictionaries.
hashfunction: Afunctionusedbyahashtabletocomputethelocationforakey.
9.7. Exercises
115
histogram: Asetofcounters.
implementation: Awayofperformingacomputation.
item: Anothernameforakey-valuepair.
key: Anobjectthatappearsinadictionaryasthefirstpartofakey-valuepair.
key-valuepair: Therepresentationofthemappingfromakeytoavalue.
lookup: Adictionaryoperationthattakesakeyandfindsthecorrespondingvalue.
nestedloops: Whenthereisoneormoreloops“inside”ofanotherloop. . The
innerlooprunstocompletioneachtimetheouterlooprunsonce.
value: Anobjectthatappearsinadictionaryasthesecondpartofakey-value
pair.Thisismorespecificthanourprevioususeoftheword“value.”
9.7 Exercises
Exercise9.3 Writeaprogramthatcategorizeseachmailmessagebywhichdayof
theweekthecommitwasdone.Todothislookforlineswhichstartwith“From”,
thenlookforthethirdwordandthenkeeparunningcountofeachofthedays
oftheweek. Attheendoftheprogramprintoutthecontentsofyourdictionary
(orderdoesnotmatter).
Sample Line:
From stephen.marquard@uct.ac.za Sat Jan
5 09:14:16 2008
Sample Execution:
python dow.py
Enter a a file name: mbox-short.txt
{
'
Fri
'
: 20,
'
Thu
'
: 6,
'
Sat
'
: 1}
Exercise9.4 Writeaprogramtoreadthroughamaillog,andfigureoutwhohad
themostmessagesinthefile. Theprogramlooksfor“From”linesandtakesthe
secondparameteronthoselinesasthepersonwhosentthemail.
TheprogramcreatesaPythondictionarythatmapsthesender’saddresstothetotal
numberofmessagesforthatperson.
Afterallthedatahasbeenreadtheprogramlooksthroughthedictionaryusing
amaximumloop(seeSection5.7.2)tofindwhohasthemostmessagesandhow
manymessagesthepersonhas.
Enter a a file name: mbox-short.txt
cwen@iupui.edu 5
Enter a a file name: mbox.txt
zqian@umich.edu 195
116
Chapter9. Dictionaries
Exercise9.5 This s programrecords the domain name(instead ofthe address)
wherethemessagewassentfrominsteadofwhothemailcamefrom(i.e. the
wholee-mailaddress). Attheendoftheprogramprintoutthecontentsofyour
dictionary.
python schoolcount.py
Enter a a file name: mbox-short.txt
{
'
media.berkeley.edu
'
: 4,
'
uct.ac.za
'
: 6,
'
umich.edu
'
: 7,
'
gmail.com
'
: 1,
'
caret.cam.ac.uk
'
: 1,
'
iupui.edu
'
: 8}
Documents you may be interested
Documents you may be interested