程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-06(2)

python中使用print对齐输出文本

发布于2019-08-20 11:00     阅读(1591)     评论(0)     点赞(10)     收藏(3)


用print()对齐输出文本的时候发现有中文的文本长度就不可控情况如下:
最近写了一个小爬虫 去爬取中国天气网的城市天气预报并打印结果
完整代码:

import json
import requests
from lxml import etree
class WeatherSpider():
    def __init__(self,key):
        self.key = key
        with open('city.json', 'r')as f:
            result = json.load(f)
            num = result[key]
            self.url = 'http://www.weather.com.cn/weather/{}.shtml'.format(num)
        self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}
        self.day_list = list()
        self.weather_list = list()
        self.temperature_list = list()
        self.wind_list = list()


    # 1 请求数据
    def get_data(self):
        data = requests.get(self.url,headers = self.headers).content.decode('utf-8')
        # print(data)
        Xpath_data = etree.HTML(data)
        return Xpath_data

    # 2 分析数据
    def analyse_data(self,data):
        self.day_list = data.xpath('//div[@id="7d"]/ul/li/h1/text()')

        self.weather_list = data.xpath('//div[@id="7d"]/ul/li/p/@title')

        self.temperature_list = list()
        count = 0
        for i in range(1,8):
            temperature_1 = data.xpath('//div[@id="7d"]/ul/li[{}]/p[@class="tem"]/span/text()'.format(i))
            temperature_2 = data.xpath('//div[@id="7d"]/ul/li[{}]/p[@class="tem"]/i/text()'.format(i))
            if temperature_1 == []:
                temperature = temperature_2[0]
            else:
                temperature = temperature_1[0] +'/' + temperature_2[0]
            self.temperature_list.append(temperature)


        self.wind_list = list()
        wind = data.xpath('//div[@id="7d"]/ul/li/p[@class="win"]/i/text()')
        for i  in wind:
            x = '风力:' + i
            self.wind_list.append(x)
    # 3 表现数据
    def print_data(self):
        print(self.key+'的近七天天气如下:')
        for i in range(7):
            print(self.day_list[i].rjust(10),end='')
            print(self.weather_list[i].rjust(10),end='')
            print(self.temperature_list[i].rjust(10),end='')
            print(self.wind_list[i].rjust(10))

    def Run(self):
        Xpath_data = self.get_data()
        self.analyse_data(Xpath_data)
        self.print_data()

if __name__ == '__main__':
    ans = 0
    # name = input('输出要查城市的名字:')
    try:
        WS = WeatherSpider('北京')
    except:
        print('我已经很努力了,可是还没有找到这个地方')
        ans = 1
    if ans:
        pass
    else:
        WS.Run()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74

在最后一步输出的时候发现文本老是对不齐
上图:
在这里插入图片描述
用了conter() ,rjust() ,ljust()发现都不能解决问题
像我这样有强迫症的程序员肯定受不了啊
查了半天资料发现原因是因为

py虽好,有些细节还是没有照顾到中文
这里补齐长度时中文字符的长度也按1字节计算了,
然而我们知道,utf-8中中文占用3个字节,GBK中占用了2个字节,只算作1字节显然不能对齐

解决方法
固定长度输出就可以这样写
len = 固定长度 - len(‘中文内容’.encode(‘GBK’)) + len(‘中文内容’)

好了找到原因那就动手改代码吧
只要修改 print_data 方法就好了
修改代码如下

    def print_data(self):
        print(self.key+'的近七天天气如下:')
        print('|{x:^{y}s}\t|'.format(x='天气',
                                    y=15 - len('天气'.encode('GBK')) + len('天气'))+'{x:^{y}s}\t|'.format(x='气象',
                                    y=15 - len('气象'.encode('GBK')) + len('气象'))+'{x:^{y}s}\t|'.format(x='温度',
                                    y=15 - len('温度'.encode('GBK')) + len('温  度'))+'{x:^{y}s}\t|'.format(x='风力:',
                                    y=15 - len('风力'.encode('GBK')) + len('风力')))
        for i in range(7):
            print('|{x:^{y}s}\t'.format(x=self.day_list[i],
                                        y=15-len(self.day_list[i].encode('GBK'))+len(self.day_list[i])),end='')
            print('|{x:^{y}s}\t'.format(x=self.weather_list[i],
                                        y=15 - len(self.weather_list[i].encode('GBK')) + len(self.weather_list[i])), end='')
            print('|{x:^{y}s}\t'.format(x=self.temperature_list[i],
                                        y=15 - len(self.temperature_list[i].encode('GBK')) + len(self.temperature_list[i])), end='')
            print('|{x:^{y}s}\t|'.format(x=self.wind_list[i],
                                        y=15 - len(self.wind_list[i].encode('GBK')) + len(self.wind_list[i])))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

改好代码来测试一波:
在这里插入图片描述
发现温度这里又有一点小问题
在改改代码测试一波
在这里插入图片描述
发现原来问题出在温度两个字太短了不能跳到下一个制表符位置上,这个简单加长一下长度让他跳到下一个制表符就好了嘛
修改代码如下:

'{x:^{y}s}\t|'.format(x='温度',y=15 - len('温度'.encode('GBK')) + len('温  度'))
  • 1

小伙伴可能说好像没什么区别啊
实际上是把温度之间加了空格让他多加几个长度就能跳到下一个制表符啦

在测试别的城市
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

好了应该是没问题了 下面配上几个链接
1,菜鸟教程里面format() 方法的教程
link.
2,我参考的链接
link.



所属网站分类: 技术文章 > 博客

作者:滴水

链接:https://www.pythonheidong.com/blog/article/49055/29bad40a62510d9fe974/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

10 0
收藏该文
已收藏

评论内容:(最多支持255个字符)