DataAnalysis-讀取本地數據

来源:https://www.cnblogs.com/wztlink1013/archive/2020/04/15/12708525.html
-Advertisement-
Play Games

數據分析當中讀取本地數據,txt,excel,csv,json,SQLite,SqLite_json等數據類型 ...


一、TXT文件操作

讀取全部內容

import numpy as np
import pandas as pd
txt_filename = './files/python_wiki.txt'

# 打開文件
file_obj = open(txt_filename,'r')

# 讀取整個文件內容
all_content = file_obj.read()

# 關閉文件
file_obj.close()

print (all_content)
Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.[24][25] Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.[26][27] The language provides constructs intended to enable writing clear programs on both a small and large scale.[28]
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.[29]
Python interpreters are available for many operating systems, allowing Python code to run on a wide variety of systems. CPython, the reference implementation of Python, is open source software[30] and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation.

逐行讀取

txt_filename = './files/python_wiki.txt'

# 打開文件
file_obj = open(txt_filename, 'r')

# 逐行讀取
line1 = file_obj.readline()
print (line1)
Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.[24][25] Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.[26][27] The language provides constructs intended to enable writing clear programs on both a small and large scale.[28]
# 繼續讀下一行【不會全部讀完】
line2 = file_obj.readline()
print (line2)

# 關閉文件
file_obj.close()
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.[29]

讀取全部內容,返回列表

txt_filename = './files/python_wiki.txt'

# 打開文件
file_obj = open(txt_filename, 'r')

lines = file_obj.readlines()

for i, line in enumerate(lines):
    print ('%i: %s' %(i, line))

# 關閉文件
file_obj.close()
0: Python is a widely used high-level, general-purpose, interpreted, dynamic programming language.[24][25] Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java.[26][27] The language provides constructs intended to enable writing clear programs on both a small and large scale.[28]

1: Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.[29]

2: Python interpreters are available for many operating systems, allowing Python code to run on a wide variety of systems. CPython, the reference implementation of Python, is open source software[30] and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation.

寫操作

txt_filename = './files/test_write.txt'

# 打開文件
file_obj = open(txt_filename, 'w')

# 寫入全部內容
file_obj.write("《Python數據分析》")
file_obj.close()

txt_filename = './files/test_write.txt'

# 打開文件
file_obj = open(txt_filename, 'w')

# 寫入字元串列表
lines = ['這是第%i行\n' %n for n in range(10)]
file_obj.writelines(lines)
file_obj.close()

with語句

txt_filename = './files/test_write.txt'
with open(txt_filename, 'r') as f_obj:
    print (f_obj.read())

這是第0行
這是第1行
這是第2行
這是第3行
這是第4行
這是第5行
這是第6行
這是第7行
這是第8行
這是第9行

二、CSV文件操作

pandas讀csv文件

根據路徑導入數據以及指定的列

import pandas as pd
filename = './files/presidential_polls.csv'
df = pd.read_csv(filename, usecols=['cycle', 'type', 'startdate'])#導入指定列
print (type(df))
print (df.head())
<class 'pandas.core.frame.DataFrame'>
   cycle        type   startdate
0   2016  polls-plus  10/25/2016
1   2016  polls-plus  10/27/2016
2   2016  polls-plus  10/27/2016
3   2016  polls-plus  10/20/2016
4   2016  polls-plus  10/20/2016

引用指定的列

cycle_se = df['cycle']
print (type(cycle_se))
print (cycle_se.head())
<class 'pandas.core.series.Series'>
0    2016
1    2016
2    2016
3    2016
4    2016
Name: cycle, dtype: int64

多層索引成dataframe類型

filename = './files/presidential_polls.csv'
df1 = pd.read_csv(filename,usecols=['cycle', 'type', 'startdate','state','grade'],index_col = ['state','grade'])
print(df1.head())
                cycle        type   startdate
state    grade                               
U.S.     B       2016  polls-plus  10/25/2016
         A+      2016  polls-plus  10/27/2016
Virginia A+      2016  polls-plus  10/27/2016
Florida  A       2016  polls-plus  10/20/2016
U.S.     B+      2016  polls-plus  10/20/2016

跳過指定的行

filename = './files/presidential_polls.csv'
df2 = pd.read_csv(filename,usecols=['cycle', 'type', 'startdate','state','grade'],skiprows=[1, 2, 3])
print(df2.head())
   cycle        type         state   startdate grade
0   2016  polls-plus       Florida  10/20/2016     A
1   2016  polls-plus          U.S.  10/20/2016    B+
2   2016  polls-plus          U.S.  10/22/2016     A
3   2016  polls-plus          U.S.  10/26/2016    A-
4   2016  polls-plus  Pennsylvania  10/25/2016    B-

pandas寫csv文件

·to_csv裡面的index參數作用?===可能是不要索引的意思。

filename = './files/pandas_output.csv'
df.to_csv(filename, index=None)

三、JSON文件操作

json讀操作

import json

filename = './files/global_temperature.json'
with open(filename, 'r') as f_obj:
    json_data = json.load(f_obj)

# 返回值是dict類型
print (type(json_data))
<class 'dict'>
print (json_data.keys())
dict_keys(['description', 'data'])

json轉CSV

#print json_data['data'].keys()
print (json_data['data'].values())
dict_values(['-0.1247', '-0.0707', '-0.0710', '-0.1481', '-0.2099', '-0.2220', '-0.2101', '-0.2559', '-0.1541', '-0.1032', '-0.3233', '-0.2552', '-0.3079', '-0.3221', '-0.2828', '-0.2279', '-0.0971', '-0.1232', '-0.2578', '-0.1172', '-0.0704', '-0.1471', '-0.2535', '-0.3442', '-0.4240', '-0.2967', '-0.2208', '-0.3767', '-0.4441', '-0.4332', '-0.3862', '-0.4367', '-0.3318', '-0.3205', '-0.1444', '-0.0747', '-0.2979', '-0.3193', '-0.2118', '-0.2082', '-0.2152', '-0.1517', '-0.2318', '-0.2161', '-0.2510', '-0.1464', '-0.0618', '-0.1506', '-0.1749', '-0.2982', '-0.1016', '-0.0714', '-0.1214', '-0.2481', '-0.1075', '-0.1445', '-0.1173', '-0.0204', '-0.0318', '-0.0157', '0.0927', '0.1974', '0.1549', '0.1598', '0.2948', '0.1754', '-0.0013', '-0.0455', '-0.0471', '-0.0550', '-0.1579', '-0.0095', '0.0288', '0.0997', '-0.1118', '-0.1305', '-0.1945', '0.0538', '0.1145', '0.0640', '0.0252', '0.0818', '0.0924', '0.1100', '-0.1461', '-0.0752', '-0.0204', '-0.0112', '-0.0282', '0.0937', '0.0383', '-0.0775', '0.0280', '0.1654', '-0.0698', '0.0060', '-0.0769', '0.1996', '0.1139', '0.2288', '0.2651', '0.3024', '0.1836', '0.3429', '0.1510', '0.1357', '0.2308', '0.3710', '0.3770', '0.2982', '0.4350', '0.4079', '0.2583', '0.2857', '0.3420', '0.4593', '0.3225', '0.5185', '0.6335', '0.4427', '0.4255', '0.5455', '0.6018', '0.6145', '0.5806', '0.6583', '0.6139', '0.6113', '0.5415', '0.6354', '0.7008', '0.5759', '0.6219', '0.6687', '0.7402', '0.8990'])
# 轉換key
year_str_lst = json_data['data'].keys()
year_lst = [int(year_str) for year_str in year_str_lst]
print (year_lst)
[1880, 1881, 1882, 1883, 1884, 1885, 1886, 1887, 1888, 1889, 1890, 1891, 1892, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1939, 1940, 1941, 1942, 1943, 1944, 1945, 1946, 1947, 1948, 1949, 1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960, 1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015]
# 轉換value
temp_str_lst = json_data['data'].values()
temp_lst = [float(temp_str) for temp_str in temp_str_lst]
print (temp_lst)
[-0.1247, -0.0707, -0.071, -0.1481, -0.2099, -0.222, -0.2101, -0.2559, -0.1541, -0.1032, -0.3233, -0.2552, -0.3079, -0.3221, -0.2828, -0.2279, -0.0971, -0.1232, -0.2578, -0.1172, -0.0704, -0.1471, -0.2535, -0.3442, -0.424, -0.2967, -0.2208, -0.3767, -0.4441, -0.4332, -0.3862, -0.4367, -0.3318, -0.3205, -0.1444, -0.0747, -0.2979, -0.3193, -0.2118, -0.2082, -0.2152, -0.1517, -0.2318, -0.2161, -0.251, -0.1464, -0.0618, -0.1506, -0.1749, -0.2982, -0.1016, -0.0714, -0.1214, -0.2481, -0.1075, -0.1445, -0.1173, -0.0204, -0.0318, -0.0157, 0.0927, 0.1974, 0.1549, 0.1598, 0.2948, 0.1754, -0.0013, -0.0455, -0.0471, -0.055, -0.1579, -0.0095, 0.0288, 0.0997, -0.1118, -0.1305, -0.1945, 0.0538, 0.1145, 0.064, 0.0252, 0.0818, 0.0924, 0.11, -0.1461, -0.0752, -0.0204, -0.0112, -0.0282, 0.0937, 0.0383, -0.0775, 0.028, 0.1654, -0.0698, 0.006, -0.0769, 0.1996, 0.1139, 0.2288, 0.2651, 0.3024, 0.1836, 0.3429, 0.151, 0.1357, 0.2308, 0.371, 0.377, 0.2982, 0.435, 0.4079, 0.2583, 0.2857, 0.342, 0.4593, 0.3225, 0.5185, 0.6335, 0.4427, 0.4255, 0.5455, 0.6018, 0.6145, 0.5806, 0.6583, 0.6139, 0.6113, 0.5415, 0.6354, 0.7008, 0.5759, 0.6219, 0.6687, 0.7402, 0.899]
import pandas as pd

# 構建 dataframe
year_se = pd.Series(year_lst, name = 'year')
temp_se = pd.Series(temp_lst, name = 'temperature')
result_df = pd.concat([year_se, temp_se], axis = 1)
print (result_df.head())

# 保存csv
result_df.to_csv('./files/json_to_csv.csv', index = None)
   year  temperature
0  1880      -0.1247
1  1881      -0.0707
2  1882      -0.0710
3  1883      -0.1481
4  1884      -0.2099

寫json操作

book_dict = [{'書名':'無聲告白', '作者':'伍綺詩'}, {'書名':'我不是潘金蓮', '作者':'劉震雲'}, {'書名':'沉默的大多數 (王小波集)', '作者':'王小波'}]

filename = './files/json_output.json'
with open(filename, 'w') as f_obj:
    f_obj.write(json.dumps(book_dict, ensure_ascii=False))
# 不需要加, encoding='utf-8'參數

四、SQLite基本操作

連接資料庫

import sqlite3

db_path = './files/test.sqlite'

conn = sqlite3.connect(db_path)
cur = conn.cursor()
conn.text_factory = str  # 處理中文

獲取基本信息

cur.execute('SELECT SQLITE_VERSION()')

print ('SQLite版本:%s' %str(cur.fetchone()[0]))
SQLite版本:3.30.0

逐條插入數據

cur.execute("DROP TABLE IF EXISTS book")
cur.execute("CREATE TABLE book(id INT, name TEXT, price DOUBLE)")
cur.execute("INSERT INTO book VALUES(1,'肖秀榮考研書系列:肖秀榮(2017)考研政治命題人終極預測4套捲',14.40)")
cur.execute("INSERT INTO book VALUES(2,'法醫秦明作品集:幸存者+清道夫+屍語者+無聲的證詞+第十一根手指(套裝共5冊) (兩種封面隨機發貨)',100.00)")
cur.execute("INSERT INTO book VALUES(3,'活著本來單純:豐子愷散文漫畫精品集(收藏本)',30.90)")
cur.execute("INSERT INTO book VALUES(4,'自在獨行:賈平凹的獨行世界',26.80)")
cur.execute("INSERT INTO book VALUES(5,'當你的才華還撐不起你的夢想時',23.00)")
cur.execute("INSERT INTO book VALUES(6,'巨人的隕落(套裝共3冊)',84.90)")
cur.execute("INSERT INTO book VALUES(7,'孤獨深處(收錄雨果獎獲獎作品《北京摺疊》)',21.90)")
cur.execute("INSERT INTO book VALUES(8,'世界知名企業員工指定培訓教材:所謂情商高,就是會說話',22.00)")
<sqlite3.Cursor at 0x2d2d64e7c00>

批量插入數據

books = (
    (9, '人間草木', 30.00),
    (10,'你的善良必須有點鋒芒', 20.50),
    (11, '這麼慢,那麼美', 24.80),
    (12, '考拉小巫的英語學習日記:寫給為夢想而奮鬥的人(全新修訂版)', 23.90)
)
cur.executemany("INSERT INTO book VALUES(?, ?, ?)", books)
<sqlite3.Cursor at 0x2d2d64e7c00>
conn.commit()

查找數據

cur.execute('SELECT * FROM book')
rows = cur.fetchall()

# 通過索引號訪問
for row in rows:
    print ('序號: %i, 書名: %s, 價格: %.2f' %(row[0], row[1], row[2]))
序號: 1, 書名: 肖秀榮考研書系列:肖秀榮(2017)考研政治命題人終極預測4套捲, 價格: 14.40
序號: 2, 書名: 法醫秦明作品集:幸存者+清道夫+屍語者+無聲的證詞+第十一根手指(套裝共5冊) (兩種封面隨機發貨), 價格: 100.00
序號: 3, 書名: 活著本來單純:豐子愷散文漫畫精品集(收藏本), 價格: 30.90
序號: 4, 書名: 自在獨行:賈平凹的獨行世界, 價格: 26.80
序號: 5, 書名: 當你的才華還撐不起你的夢想時, 價格: 23.00
序號: 6, 書名: 巨人的隕落(套裝共3冊), 價格: 84.90
序號: 7, 書名: 孤獨深處(收錄雨果獎獲獎作品《北京摺疊》), 價格: 21.90
序號: 8, 書名: 世界知名企業員工指定培訓教材:所謂情商高,就是會說話, 價格: 22.00
序號: 9, 書名: 人間草木, 價格: 30.00
序號: 10, 書名: 你的善良必須有點鋒芒, 價格: 20.50
序號: 11, 書名: 這麼慢,那麼美, 價格: 24.80
序號: 12, 書名: 考拉小巫的英語學習日記:寫給為夢想而奮鬥的人(全新修訂版), 價格: 23.90
conn.row_factory = sqlite3.Row
cur = conn.cursor() 
cur.execute('SELECT * FROM book')
rows = cur.fetchall()

# 通過列名訪問
for row in rows:
    print ('序號: %i, 書名: %s, 價格: %.2f' %(row['id'], row['name'], row['price']))
序號: 1, 書名: 肖秀榮考研書系列:肖秀榮(2017)考研政治命題人終極預測4套捲, 價格: 14.40
序號: 2, 書名: 法醫秦明作品集:幸存者+清道夫+屍語者+無聲的證詞+第十一根手指(套裝共5冊) (兩種封面隨機發貨), 價格: 100.00
序號: 3, 書名: 活著本來單純:豐子愷散文漫畫精品集(收藏本), 價格: 30.90
序號: 4, 書名: 自在獨行:賈平凹的獨行世界, 價格: 26.80
序號: 5, 書名: 當你的才華還撐不起你的夢想時, 價格: 23.00
序號: 6, 書名: 巨人的隕落(套裝共3冊), 價格: 84.90
序號: 7, 書名: 孤獨深處(收錄雨果獎獲獎作品《北京摺疊》), 價格: 21.90
序號: 8, 書名: 世界知名企業員工指定培訓教材:所謂情商高,就是會說話, 價格: 22.00
序號: 9, 書名: 人間草木, 價格: 30.00
序號: 10, 書名: 你的善良必須有點鋒芒, 價格: 20.50
序號: 11, 書名: 這麼慢,那麼美, 價格: 24.80
序號: 12, 書名: 考拉小巫的英語學習日記:寫給為夢想而奮鬥的人(全新修訂版), 價格: 23.90
conn.close()

五、SQLite_json操作

import sqlite3

db_path = './files/test_join.sqlite'

conn = sqlite3.connect(db_path)
cur = conn.cursor()
# 建 depaetment 表,並插入數據
cur.execute("DROP TABLE IF EXISTS department")
cur.execute("CREATE TABLE department(\
                id INT PRIMARY KEY NOT NULL, \
                dept CHAR(50) NOT NULL, \
                emp_id INT NOT NULL)")
depts = (
        (1, 'IT Builing', 1),
        (2, 'Engineerin', 2),
        (3, 'Finance', 7)
)
cur.executemany("INSERT INTO department VALUES(?, ?, ?)", depts)
<sqlite3.Cursor at 0x2d2d64f70a0>
conn.commit()

CROSS JOIN 交叉連接

cur.execute("SELECT emp_id, name, dept FROM company CROSS JOIN department;")
rows = cur.fetchall()
for row in rows:
    print (row)
# 建 company 表,並插入數據
cur.execute("DROP TABLE IF EXISTS company")
cur.execute("CREATE TABLE company(\
                    id INT PRIMARY KEY NOT NULL, \
                    name CHAR(50) NOT NULL, \
                    age INT NOT NULL, \
                    address CHAR(50) NOT NULL,\
                    salary DOUBLE NOT NULL)")
companies = (
        (1, 'Paul', 32, 'California', 20000.0),
        (2, 'Allen', 25, 'Texas', 15000.0),
        (3, 'Teddy', 23, 'Norway', 20000.0),
        (4, 'Mark', 25, 'Rich-Mond', 65000.0),
        (5, 'David', 27, 'Texas', 85000.0),
        (6, 'Kim', 22, 'South-Hall', 45000.0),
        (7, 'James', 24, 'Houston', 10000.0)
)
cur.executemany("INSERT INTO company VALUES (?, ?, ?, ?, ?)", companies)
<sqlite3.Cursor at 0x2d2d64f70a0>

INNER JOIN 內連接

cur.execute("SELECT emp_id, name, dept FROM company INNER JOIN department \
            ON company.id = department.emp_id;")
rows = cur.fetchall()
for row in rows:
    print (row)
(1, 'Paul', 'IT Builing')
(2, 'Allen', 'Engineerin')
(7, 'James', 'Finance')

OUTER JOIN 外連接

# 左連接
cur.execute("SELECT emp_id, name, dept FROM company LEFT OUTER JOIN department \
            ON company.id = department.emp_id;")
rows = cur.fetchall()
for row in rows:
    print (row)
(1, 'Paul', 'IT Builing')
(2, 'Allen', 'Engineerin')
(None, 'Teddy', None)
(None, 'Mark', None)
(None, 'David', None)
(None, 'Kim', None)
(7, 'James', 'Finance')
# 右連接 (目前不支持)
cur.execute("SELECT emp_id, name, dept FROM company RIGHT OUTER JOIN department \
            ON company.id = department.emp_id;")
rows = cur.fetchall()
for row in rows:
    print (row)
---------------------------------------------------------------------------

OperationalError                          Traceback (most recent call last)

<ipython-input-41-ce0fc573748b> in <module>
      1 # 右連接 (目前不支持)
      2 cur.execute("SELECT emp_id, name, dept FROM company RIGHT OUTER JOIN department \
----> 3             ON company.id = department.emp_id;")
      4 rows = cur.fetchall()
      5 for row in rows:


OperationalError: RIGHT and FULL OUTER JOINs are not currently supported
# 右連接,交換兩張表
cur.execute("SELECT emp_id, name, dept FROM department LEFT OUTER JOIN company \
            ON company.id = department.emp_id;")
rows = cur.fetchall()
for row in rows:
    print (row)
(1, 'Paul', 'IT Builing')
(2, 'Allen', 'Engineerin')
(7, 'James', 'Finance')
sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
      ON COMPANY.ID = DEPARTMENT.EMP_ID;
  File "<ipython-input-43-a0833b733075>", line 1
    sqlite> SELECT EMP_ID, NAME, DEPT FROM COMPANY LEFT OUTER JOIN DEPARTMENT
                        ^
SyntaxError: invalid syntax

六、Excel文件操作

pandas.read_excel(io, sheet_name=0, header=0, names=None, index_col=None, usecols=None, squeeze=False, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skiprows=None, nrows=None, na_values=None, keep_default_na=True, verbose=False, parse_dates=False, date_parser=None, thousands=None, comment=None, skipfooter=0, convert_float=True, mangle_dupe_cols=True, **kwds)

df_fujian = pd.read_excel("./datafiles/fujian.xlsx",sheet_name='日數據')


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 通俗理解spring源碼(三)—— 獲取xml的驗證模式 上一篇講到了xmlBeanDefinitionReader.doLoadBeanDefinitions(inputSource, encodedResource.getResource())方法。 protected int doLoadBe ...
  • 開啟兩個環境變數 go env -w GO111MODULE=ongo env -w GOPROXY=https://goproxy.cn,direct 在自己的項目里 go mod init 然後如果有引用github上的包 , 直接go mod tidy ,就會自動安裝 golang開啟go m ...
  • 這兩天做了一個小測試是抓的天氣信息本來想存資料庫,後來覺得還是存csv比較好,使用方便,但是在使用的過程中,發現存中文的時候會出現亂碼的情況,查了一下資料,跟大家分享一下python3中存csv亂碼的問題。 親測在python2中是不能設置這個編碼格式,不支持這個方式。 ...
  • 前言 文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯繫我們以作處理。 PS:如有需要Python學習資料的小伙伴可以加點擊下方鏈接自行獲取http://t.cn/A6Zvjdun 如何破解iphone登陸密碼 今天看了一篇關於如何破解iphone ...
  • 值多態是一種介於傳統多態與類型擦除之間的多態實現方式,借鑒了值語義,保留了繼承,在單繼承的適用範圍內,程式和程式員都能從中受益。 ...
  • 泛型數組列表 為什麼要使用泛型數組列表 使用常規數組,界限固定,不易擴展。 int[]nums =new int[size]; 這個數組的長度固定為了size的大小。但如果使用數組列表就可以自動開闢空間,存放元素。 泛型數組列表ArrayList的定義 1.無參的 ArrayList integer ...
  • [toc] 1、分析網頁 當我們去爬取網頁時,首先要做的就是先分析網頁結構,然後就會發現相應的規律,如下所示: 生成鏈接:從網頁鏈接的規律中可得寫一個for迴圈即可生成它的鏈接,其中它的間隔為25,程式如下: 得到的結果如下: 2、請求伺服器 在爬取網頁之前,我們要向伺服器發出請求 2.1導入包 沒 ...
  • 前言 文的文字及圖片來源於網路,僅供學習、交流使用,不具有任何商業用途,版權歸原作者所有,如有問題請及時聯繫我們以作處理。 PS:如有需要Python學習資料的小伙伴可以加點擊下方鏈接自行獲取http://t.cn/A6Zvjdun 最近找工作,爬蟲面試的一個面試題。涉及的反爬還是比較全面的,結果公 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...