The following notes are collected and shared by the data analysis group of xue.cn learning group. Related background: I choose the case of Chinese word frequency statistics as a test of your basic command of Python.
Here are 2 specific practical skills:
- How to handle file reading flexibly
- How to process the data into the data type you want
Method 1:
When copying an article, assign the content directly to a variable and save it to a.py file. Then, in the script, import it.
The article. Py file that stores articles
content = """ Copied article content """
Copy the code
The file my_code.py that stores the script
from article import content
Copy the code
Method 2:
Copy the content of the article into a TXT file (usually people do this). Read file contents directly.
Strings can be generated directly with the read() method.
with open('test.txt'.'r',encoding='utf-8') as f:
content = f.read()
Copy the code
Method 3:
Use readlines() or readline() with a for iteration to compose the string itself.
For example, the BSDZSZ code snippet:
data = ' '
with open('test.txt'.'r',encoding='utf-8') as f:
for line in f.readlines():
line = line.strip()
data += line
Copy the code
Of course, there are more ways. The above 3 methods are very friendly to zero-based newcomers, and they can be done just by mastering a little bit of skin.
From this method example, you can get a sense that the same data (article content) may be stored in various forms (a string variable in a.py file is called in another.py file, or a regular TXT file), and we can retrieve that data in various ways.