3.9 Formatting: From Lists to Strings 格式化:从列表到字符串
Often we write a program to report a single data item, such as a particular element in a corpus that meets some complicated criterion, or a single summary statistic such as a word-count or the performance of a tagger. More often, we write a program to produce a structured result; for example, a tabulation of numbers or linguistic forms, or a reformatting(格式变换) of the original data. When the results to be presented are linguistic, textual output is usually the most natural choice. However, when the results are numerical, it may be preferable to produce graphical output. In this section, you will learn about a variety of ways to present program output.(在这一节,你将会学习各种呈现程序输出的方式。)
From Lists to Strings 从列表到字符串
The simplest kind of structured object we use for text processing is lists of words. When we want to output these to a display or a file, we must convert these lists into strings. To do this in Python we use the join() method, and specify the string to be used as the“glue”:
So ' '.join(silly) means: take all the items in silly and concatenate them as one big string, using ' ' as a spacer between the items. I.e., join() is a method of the string that you want to use as the glue. (Many people find this notation for join() counter-intuitive.) The join() method only works on a list of strings—what we have been calling a text—a complex type that enjoys(享有) some privileges(权限) in Python.
Strings and Formats 字符串和格式
We have seen that there are two ways to display the contents of an object:
The print command yields Python’s attempt to produce the most human-readable form of an object. The second method—naming the variable at a prompt—shows us a string that can be used to recreate this object. It is important to keep in mind that both of these are just strings, displayed for the benefit of you, the user. They do not give us any clue as to the actual internal representation of the object.
There are many other useful ways to display an object as a string of characters. This may be for the benefit of a human reader, or because we want to export our data to a particular file format for use in an external program.
Formatted output typically contains a combination of variables and pre-specified strings. For example, given a frequency distribution fdist, we could do:
Apart from the problem of unwanted whitespace, print statements that contain alternating variables and constants can be difficult to read and maintain. A better solution is to use string formatting expressions(字符串格式表达式).
To understand what is going on here, let’s test out the string formatting expression on its own. (By now this will be your usual method of exploring new syntax.)
The special symbols %s and %d are placeholders(占位符) for strings and (decimal) integers. We can embed these inside a string, then use the % operator to combine them. Let’s unpack this code further, in order to see this behavior up close(近距离):
We can have a number of placeholders, but following the % operator we need to specify a tuple with exactly the same number of values:
We can also provide the values for the placeholders indirectly. Here’s an example using a for loop:
The %s and %d symbols are called conversion specifiers(转换说明符). They start with the % character and end with a conversion character such as s (for string) or d (for decimal integer) The string containing conversion specifiers is called a format string(格式字符串). We combine a format string with the % operator and a tuple of values to create a complete string formatting expression.
Lining Things Up 排列
So far our formatting strings generated output of arbitrary width on the page (or screen), such as %s and %d. We can specify a width as well, such as %6s, producing a string that is padded(填补) to width 6. It is right-justified by default①, but we can include a minus sign to make it left-justified②. In case we don’t know in advance(事前) how wide a displayed value should be, the width value can be replaced with a star in the formatting string(可以用*表示宽度值), then specified using a variable③.
Other control characters are used for decimal integers and floating-point numbers. Since the percent character % has a special interpretation in formatting strings, we have to precede(在前面) it with another % to get it in the output.
An important use of formatting strings is for tabulating data. Recall that in Section 2.1 we saw data being tabulated from a conditional frequency distribution. Let’s perform the tabulation ourselves, exercising full control of headings and column widths, as shown in Example 3-5. Note the clear separation between the language processing work, and the tabulation of results.
Example 3-5. Frequency of modals in different sections of the Brown Corpus.
Recall from the listing in Example 3-1 that we used a formatting string "%*s". This allows us to specify the width of a field using a variable.
We could use this to automatically customize the column to be just wide enough to accommodate all the words, using width = max(len(w) for w in words). Remember that the comma at the end of print statements adds an extra space, and this is sufficient
to prevent the column headings from running into each other(记得在print语句后面的逗号会增加额外的空间,避免了列标题的相互影响).
Writing Results to a File 把结果写入文件
We have seen how to read text from files (Section 3.1). It is often useful to write output to files as well. The following code opens a file output.txt for writing, and saves the program output to the file.
Your Turn: What is the effect of appending \n to each string before we write it to the file? If you’re using a Windows machine, you may want to use word + "\r\n" instead. What happens if we do output_file.write(word)
When we write non-text data to a file, we must convert it to a string first. We can do this conversion using formatting strings, as we saw earlier. Let’s write the total number of words to our file, before closing it.
Caution!
You should avoid filenames that contain space characters, such as output file.txt, or that are identical except for case distinctions, e.g., Output.txt and output.TXT
Text Wrapping 文本换行
When the output of our program is text-like, instead of tabular, it will usually be necessary to wrap it so that it can be displayed conveniently. Consider the following output, which overflows its line, and which uses a complicated print statement:
We can take care of line wrapping with the help of Python’s textwrap module. For maximum clarity(清楚) we will separate each step onto its own line:
Notice that there is a linebreak between more and its following number. If we wanted to avoid this, we could redefine the formatting string so that it contained no spaces (e.g., '%s_(%d),'), then instead of printing the value of wrapped, we could print wrapped.replace('_', ' ').