JasonQiao 0 Newbie Poster

ONE

    '''you are given two file names:
fin: the input file, and
fout:the output file.

The argument maxlen is an integer > 2,
indicating the maximum length of
each line in the output file.

the function will read the fin as
a text file line by line, and 
depending on the length
(not including the new line mark \n)
of each line, do one of the following:

(1). if length <= maxlen:
   append necessary number of
   spaces (' ') to the line so that
   its length == maxlen;

(2). if length > maxlen: 
   cut from the beginning of the
   line as many segments of length
   maxlen as possible, and
   apply (1) to the last segment
   to make its length == maxlen.

and write all lines to the output file,
preserving the order of text.'''

def equalines(fin, maxlen, fout):
    with open('fin','rU') as f, open ('fout','wt') as g:
        s=[] # 先弄一个list来装 fin 的内容
        for line in f:
            line=line.rstrip('\n') # 现将每一行的换行符去掉
            if len(line) >maxlen:  # 长度大于maxlen 
                b=int(len(line)%maxlen) #那么求出余下的值
                newlist=line[len(line)-b:]+' '*int(maxlen-b)
                #将余下的值与' '相连,补足maxlen位
                s.append(newlist)
            elif len(line) < maxlen: #长度小于maxlen
                newlist=line[:]+' '*int(maxlen-len(line))
                #直接在line之后加上' ',来补足maxlen位
                s.append(newlist)
            else:
                s.append(newlist) #如果长度与maxlen相同,直接加上即可
        for i in range(len(s)):
            line='\n'.join(s[i])
            print(line,file=g)
        #将得到的s list 中的每一项,用换行符相连,而后输出到fout 里面(这里定义为g)

TWO

'''you are given a CSV file fin,
the first row of fin are names for
the corresponding columns (no names will
appear more than once). An example:

student no,first name,last name,hw3,lab3,midterm
2304893445,John,Koon,90,95,95
2303892448,John,Ball,80,90,90

And cols is a list of the column names,
in an arbitrary order, of an arbitrary length.
Those are the columns to be picked out.
You should write the name and the selected
columns as a CSV file in fout.

Continue the example above, if
   cols=['midterm','student no']
you should write to a file named fout
the following contents:

midterm,student no
95,2304893445
90,2303892448

The order of records should be preserved.
'''

def colselect(fin, cols, fout):
    with open('fin', "rU") as f, open ('fout','wt') as g:
        s=[] # 先制作一个list来装 fin 的内容
        for line in f:
            line=line.rstrip('\n').split(',')
            # 现将每一行的换行符去掉,并且将每一行由string拆分为list
            indexlist=[] #设置一个空的list
            for i in len(cols):
                a=line.index(cols[i])#记录已经变为list的line中与cols对应的条目
                # 并且保证顺序
                indexlist.append(a)
            b=','.join(line[i] for i in indexlist)
            #重新用','来连接从每一行中与cols对应的项目
            print (b,file=g)

THREE

    '''Parse Stock prices. Create a function that will
decode the old-style fractional stock price. The price
can be a simple floating point number or it can be a
fraction, for example, 4 5/8.

Develop two patterns, one for numbers with optional
decimal places and another for a number with a space
and a fraction. Write a function that accepts a string
and checks both patterns, returning the correct decimal
price for whole numbers (e.g., 14), decimal prices
(e.g., 5.28) and fractional prices (27 1/4).

For the fractional prices (27 1/4), only whole numbers
are allowed in it, and the fractional part must be proper,
that is, it must in the (0,1) range, excluding 0 and 1.
Otherwise, your fuction should return float('nan'),
that is, Not-A-Number.

return a float type object representing the parsed price.

For example,

stock_price('27 1/4') returns float('27.25')
stock_price('27 4/2') returns float('nan')
stock_price('1/2') returns float('0.5')
stock_price('half') returns float('nan')
stock_price('0.1/0.2') returns float('nan')
stock_price('0.2') returns float('0.2')
stock_price('2') returns float('2')
'''

def stock_price(price):
    if price.count('.')==1:
        while price.count('/')==0:# 如果有'.'和'/',那么pretest将其输出为'nan'
           return float(price) #如果有'.'没有'/',那么就是直接转为float
        return float('nan')
    elif price.count('.')==0: 
        if  price.count('/')==1:#如果没有'.',有'/'
            b=price.find('/')  #找到'/'和 ' '所在的位置(如果有' '的话)
            c=price.find(' ')
            if price[b-1]<price[b+1] and price.count(' ')==1:#前面的数字小于后面的数字
                return float(int(price[:c])+int(price[c+1:b])/int(price[b+1:]))
            #找到位置后,将string分开并且转成int,此时有' ',那么将' '前面的数字和后面'/'
            #前后的数字相除即可
            elif price[b-1]<price[b+1] and price.count(' ')==0:#前面的数字小于后面的数字
                return float(int(price[:b])/int(price[b+1:]))
            #如果没有' ',那么直接将'/'前后的数字相除即可
            else:
                return float('nan')
            #如果'/'前面的数字大于后面的数字,就输出'nan'
        elif price.count('/')==0: #既没有'.'也没有'/'
            if price.isdigit()==True:#如果是数字,没有' '
                return float(price)
            else: #如果不是数字,包括其中包含' '
                return float('nan')
    else: # 多于两个'.的输入一定无效
        return float('nan')

FOUR

    '''you are given  a bunch of phone
numbers in a file whose name is
provided by parameter name_fin,
each line has exectly one phone number.
They look like this:

8144658695
812 673 5748
812  453   6783
812-348 7584
(617) 536 6584
834-674-8595

use some regexes to reformat
the numbers using the sub() method
so that the phone numbers look like

814+465-8695
812+673-5748
812+453-6783
812+348-7584
617+536-6584
834+674-8595

and write back to a file whose name is provided
by parameter name_fout, each line with one
phone number, in the same order as in the input file.'''

def phone_numbers(name_fin, name_fout):
    with open('name_fin','rU') as f, open('name_fout','wt') as g:
        s=[]# 先搞一个list来装 fin 的内容
        for line in f:
            line=line.rstrip('\n') # 现将每一行的换行符去掉
            x=compile(r'(\d{3})\D*(\d{3})\D*(\d{4})' )
            #将 fin 中每一行的内容先进行转换,分成三个部分
            s.append((x.sub( r'\1+\2-\3', line ))
            #再将每一行进行替换,换成题目要求的形式
            #第一部分和第二部分以'+'相连,第二部分和第三部分以'—'相连
        line='\n'.join(s[i] for i in range(len(s))
        print(line,file=g)
        #将得到的s list 中的每一项,用换行符相连,而后输出到fout 里面(这里定义为g)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.