Tôi đã gặp sự cố này ngày hôm nay và tôi đã đưa ra một giải pháp khác. Nếu bạn lo lắng về những gì nó trông giống như khi in, bạn có thể thay thế đối tượng tệp stdout bằng một tùy chỉnh, khi write() được gọi, tìm kiếm bất kỳ thứ gì trông giống như float, và thay thế chúng bằng định dạng của riêng bạn chúng.
class ProcessedFile(object):
def __init__(self, parent, func):
"""Wraps 'parent', which should be a file-like object,
so that calls to our write transforms the passed-in
string with func, and then writes it with the parent."""
self.parent = parent
self.func = func
def write(self, str):
"""Applies self.func to the passed in string and calls
the parent to write the result."""
return self.parent.write(self.func(str))
def writelines(self, text):
"""Just calls the write() method multiple times."""
for s in sequence_of_strings:
self.write(s)
def __getattr__(self, key):
"""Default to the parent for any other methods."""
return getattr(self.parent, key)
if __name__ == "__main__":
import re
import sys
#Define a function that recognises float-like strings, converts them
#to floats, and then replaces them with 1.2e formatted strings.
pattern = re.compile(r"\b\d+\.\d*\b")
def reformat_float(input):
return re.subn(pattern, lambda match: ("{:1.2e}".format(float(match.group()))), input)[0]
#Use this function with the above class to transform sys.stdout.
#You could write a context manager for this.
sys.stdout = ProcessedFile(sys.stdout, reformat_float)
print -1.23456
# -1.23e+00
print [1.23456] * 6
# [1.23e+00, 1.23e+00, 1.23e+00, 1.23e+00, 1.23e+00, 1.23e+00]
print "The speed of light is 299792458.0 m/s."
# The speed of light is 3.00e+08 m/s.
sys.stdout = sys.stdout.parent
print "Back to our normal formatting: 1.23456"
# Back to our normal formatting: 1.23456
Sẽ không tốt nếu bạn chỉ đặt số vào một chuỗi, nhưng cuối cùng bạn có thể muốn viết chuỗi đó vào một số loại tệp ở đâu đó và bạn có thể bọc tệp đó đối tượng trên. Rõ ràng có một chút chi phí hiệu suất.
Cảnh báo công bằng: Tôi chưa thử nghiệm điều này trong Python 3, tôi không biết liệu nó có hoạt động hay không.
Vấn đề là tôi đã nổi trong danh sách, và khi tôi in (danh sách) tôi không kiểm soát được điều đó. (Điều này cũng áp dụng cho các đối tượng khác, btw). Sửa đổi mã nguồn là khả thi như tôi biết C, nhưng không phải là chính xác những gì tôi đã nghĩ đến. Cảm ơn. – AkiRoss
@AkiRoss: Vì vậy, sau đó những gì bạn muốn sửa chữa là danh sách, không phải là nổi ... –
@AkiRoss, nếu bạn muốn kiểm soát nhiều hơn chỉ in các mục riêng lẻ. –