[Tutor] Another parsing question
Andrei
project5 at redrival.net
Sat Mar 31 20:46:42 CEST 2007
Hello Jay,
Jay Mutter III wrote:
> but still haven't gotten he first one.
>
<snip>
>> for line in s:
>> jay = patno.findall(line)
>> print jay
>>
>> which yields the following
>>
>> [('1', '337', '912')]
>> [('1', '354', '756')]
<snip>
>> if i try to write to a file instead of print to the screen using
>> p2.write(jay)
>> i get the message
>>
>> Traceback (most recent call last):
>> File "patentno.py", line 12, in ?
>> p2.write(jay)
>> TypeError: argument 1 must be string or read-only character buffer,
>> not list
Have a look at the output of print jay in the loop: it's a list
containing a single tuple. The traceback is telling you that write()
expects to get a string, not a list - you'll have to convert your list
to a string. There are more ways to do this, depending on your needs.
You could for example simply use p2.write(str(jay)), which will put in
the file exactly what you see on the screen.
You could also pretty-format it like this:
>>> prettyjay = "".join(jay[0])
>>> p2.write(prettyjay + "\n")
This will yield strings like "1336012".
On a side-note, you should pay attention to the way you name your
variables. prompt1 is descriptive, but strongly suggests that you have a
prompt2, prompt3, etc. lurking somewhere in the code - and indeed, you
do have a prompt2. Imagine a large program with many prompts, it would
have prompt458, prompt2893. What happens if you remove prompt45 -
renumber all the other ones?
Not only that, prompt1 is actually a filename, while the name suggests
it's simply a string shown to the user. It would be better to name them
e.g. InputFileName and OutputFileName and the files themselves InputFile
and OutputFile instead of p1/p2. patno suggests it's shorthand notation
for PatternNumber - while it's in fact a regex, not a number at all.
Naming variables after yourself, movie stars, pets or other frivolities
- flattering as it may be - will become problematic when a couple of
months later you're wondering why the application crashes upon adding
Fido to DarthVader, appending the result to ApplePie and writing that to
PamelaAnderson.
Yours,
Andrei
=====
Mail address in header catches spam. Real contact info:
''.join([''.join(s) for s in zip(
"poet at aao.l pmfe!Pes ontuei ulcpss edtels,s hr' one oC.",
"rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")])
More information about the Tutor
mailing list