Python五期爬虫作业

【Python爬虫】第二周练习(二)

2018-01-02  本文已影响11人  Doggy米
# -*- coding: utf-8 -*-

import csv

# 一、创建txt文件,写入文本如下:
# name,sex
# '攀攀','男'
# 提示:换行写入'\n'

with open("data.txt", "w", encoding="utf-8") as file:
    file.write("name,sex")
    file.write('\n')
    file.write("'攀攀','男'")

# 二、把创建好的txt文件转换为csv文件,如视频中csv格式
# 提示:逐行读取,利用split方法。

with open("data.txt", "r", encoding="utf-8" as source_file:
    with open('stocks.csv', "w", newline='') as target_file:
        for line in source_file:
            writer = csv.writer(target_file)
            list_str = line.strip().split(',')
            print(list_str)
            writer.writerow(list_str)


# 定义g到kg的转换函数,效果如图:1234g = 1.234kg

def convert(number_g):
    if isinstance(number_g, int):
        return number_g / 1000
    raise Exception("参数错误")


print("1234g", "=", str(convert(1234)) + "Kg")


# 输入姓名,隐藏名字,效果如图:
# 提示:字符串的索引切片、字符串的replace方法

def hide_name(name):
    return name[0:1] + ('*' * len(name[1:]))


print(hide_name("哇咔咔"))


# 被2或者被3整除的正整数依次是:2,3,4,6,8,9,10,12,14,15,16,18...
# 定义一个函数,求第n个被2或者被3整除的正整数是多少?

def get_num(index_num):
num_result = 0
index_count = 0
while index_count < index_num:
    num_result += 1
    if num_result % 2 == 0 or num_result % 3 == 0:
        index_count += 1
return num_result


for num in range(1, 100):
    print(get_num(num))
上一篇下一篇

猜你喜欢

热点阅读