CH1

Section 1: Open a file and converte into a dict

This section will show you how I try to open a file, and then creat a dict. I have so many questions:

Q0: How to fetch the 'weather_info.txt'?

Use GitHub sounds coooooool. It offer these Git command:

  • git remote
  • git fetch
  • git pull

Answer: NO,thanks, I think GitHub Desktop is totally perfect for me... I will come back to Git after I finished all the tasks of this course.But not now. You have my word.

Q1: How to read a file? That's hard to choose wether use f.read() or f.readline()? Should I use the open() function to open the file first? What does f.read() mean?

Q2:It's all about "DICT". How to turn the weather_info.txt into a dict? How to construct the cityname to be "key" and the weather information of this city to be "value"? Make them to be the format as the "key-value" pairs ? How to converte the strings which separated by comma(the defaut type of this text) to the dict?

So far to my understanding: We open a file, and give the file a command by using the . (a dot), the name of the function, that f.read() says, "Hey f! Do your read command with no parameters!"

AND: I carried on reading the office docs, found the keyword -"with" is good for open the file objects. With "with",the file can be properly closed after its suite finishes so that it can free up any system resources taken up by the open file.

It looks like that way:

with open('workfile', 'r') as f: ... read_data = f.read()

Answer to Q1 + Q2:

I tried different formats to run the code so many times,and ENDED here:

file = open('weather_info.txt','r',encoding = 'utf-8')
    for line in file.readlines():
        data = line.split(',')  
        dict_weather[data[0]] = data[1]

(1)The second line "for" is very useful.

For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code

It take me long time to get the meaning of "for line in file.readlines():"

f.readlines() means to read a file in a list,so adding "for line in" means to read all the lines of this "weather_info.txt"file;and it followed by 3-4th sentences means first read the data and then saved it as a dict.

(2) I did't use the "with", although I know we should use this keyword when dealing with file objects because with "with" the file is properly closed after its suite finishes. I will use it in the future... And I didn't use "strip"(line = line.strip('\n')), too.

(3) Do you notice the "encoding = 'utf-8''? I spent so much time on that,that's another story,I will talk about it in next section(with my tear-wet eyes...).

(4)The way to creat a dict. The key point is to set up the "key" and "value" pair.Between them through a sepecial identifier(key-value) to connect each other. I think it maybe useful to copy that code from LPIHW:

cities = {  ...(omitted) ...}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'

The 4th line of my code:

dict_weather[data[0]] = data[1]

It omitted something,actually the whole code as following:

data = line.split(',')  

# those codes are omitted
    a = line[0]
    b = line[1]
    [a] = b
# those codes are omitted

dict_weather[data[0]] = data[1]

(5)There are several ways to "open the file",the following comes from classmate, just pick them at random.

@yanzhiw (He finished the task of ch3 on ch1 !)

dict_weather = {}
for i in f:
    i = i.split(',')
    dict_weather[i[0]] = i[1].strip()

@Yifan127 (his code)

filename = "weather_info.txt"
weather_dict = {}  
weather_history = {}

def convert_txt_to_dict(filename):
    with open(filename, encoding = "utf-8") as file:
        for line in file.readlines():
            try:
                line = line.strip()
                data = line.split(',')
                # anther way to update dictory:
                # weather_dict.update({data[0]: data[1]})
                weather_dict[data[0]] = data[1]
            except:
                pass
    return weather_dict

@simpleowen (The hero who combat the shadow,and had saved me from the flame three times,so far...)

Here is his optimized version:

import datetime
def getWeatherData():  
    wd = {}
    with open(wPath,'r') as wf:
        for f in wf:
            wd[f.split(",")[0].strip()] = f.split(",")[1].strip()

The other version

@gzMichael (The guy used OOP to finished the task of ch3,here is the gitbook)

import platform,codecs

print ('Python',platform.python_version())
city_weather={}
f = codecs.open( 'weather_info.txt', 'r', 'utf-8' ) 
for lines in f.readlines():  
    line=lines.strip().split(',')
    city_weather[line[0]] = line [1]  
f.close()

SUMMY: The explicit different is someone used the function, the other not.

Flat is better than nested. Simple is better than complex.

So, which is better ? Which is more pythonic? Ha ha ha, so far I cann't tell. I just like the less one, if they can implement the same functionality.

Here is the issue about dict


This mistake I made when I try to creat a dict:

dict1 = {'name':'w', 'num':003} dict2 = {'name':'sardine2', 'num':20}
print(dict1, dict2)

output: something wring with [003],003 is invalid token?

I googled the answer,it says:

The number begined with 0 will be recognized as octal digits , the number of octal digits is 0,1,2,3,4,5,6,7. 003 more than 8-band maximum, balabalabalabala,something like that. (I don't have time and patience to verify...)

Q3:How to break a large string('weather_info.txt') down into smaller chunks, or strings?

Answer: The way to cut the string is "string.split()" function,it can separator the string while using str as the separator (splits on all whitespace if left unspecified), and returns a list of all the words in the string, optionally limiting the number of splits to num.

It's hard to understand what these words mean, so I try to find some example:

1 s='a b c' 2 print s.split(' ') 3 st='hello world' 4 print st.split('o') 5 print st.split('o',1) 6 7 --------output--------- 8 ['a', 'b', 'c'] 9 ['hell', ' w', 'rld'] 10 ['hell', ' world']

I think MAYBE I got something,but not sure... Anyway, I followed the example to write:

data = line.split(',') 

results matching ""

    No results matching ""