为什么Python3 shell中的文本格式与生成的文本文件不同?

为什么Python3 shell中的文本格式与生成的文本文件不同?,python,python-3.x,beautifulsoup,Python,Python 3.x,Beautifulsoup,我正在尝试读取网页并将格式化文本输出到文本文件。下面的代码以格式打印到shell中,但当我将其写入文件时,它会将其放在一行上(文本中有换行符/n) 我尝试过很多方法,比如不将其转换为字符串,使用BeautifulSoup中的prettify,但似乎没有一种方法能够生成具有格式的文本文件。我想我错过了一些基本的东西。任何帮助或指导都将不胜感激 # Import from urllib.request import urlopen from bs4 import BeautifulSoup #T

我正在尝试读取网页并将格式化文本输出到文本文件。下面的代码以格式打印到shell中,但当我将其写入文件时,它会将其放在一行上(文本中有换行符/n)

我尝试过很多方法,比如不将其转换为字符串,使用BeautifulSoup中的prettify,但似乎没有一种方法能够生成具有格式的文本文件。我想我错过了一些基本的东西。任何帮助或指导都将不胜感激

# Import 
from urllib.request import urlopen
from bs4 import BeautifulSoup

#The actual code


URL = "https://simple.wikipedia.org/wiki/castle" #The target URL
html = urlopen(URL).read()  # Reads the url to variable html
soup = BeautifulSoup(html, "lxml") # Uses BS4 to create the soup using the lxml parser
soup = soup.get_text() # Extracts the text
print(soup) # Prints to python 3.5.1 shell, formatted as I would expect


# Now writing what I have extracted to a text file
file = open("TextOutput.txt", 'w') # Creates the file and opens as write (w)
file.writelines(str(soup.encode('UTF-8'))) # Tried file.write/lines(soup), convertion to string and encoding as UTF-8 needed to avoid errors
file.close()
文件输出的示例如下所示:

b'\n\n\nCastle-简单英文维基百科,免费百科全书\n文档.documentElement.className=document.documentElement.className.replace(/(^ |\s)客户端nojs(\s |$)/,“$1客户端js$2”)\n(window.RLQ=window.RLQ | |[])push(function(){mw.config.set({“wgcononicalNamespace”:“wgcononicalSpecialGenerame”:false,“wgNamespaceNumber”:0,“wgPageName”:“Castle”,“wgTitle”:“Castle”,“wgCurRevisionId”:5333370,“wgArticleId”:15933,“wgIsArticle”:true,“wgIsRedirect”:false,“wgAction”:“视图”,“wgUserName”:null,“wgUserGroups”:“,”,“wgCategories”:[“Castles”],“wgBreakFrames”:false,“wgPageContentLanguage”:“en”,“wgPageContentModel”:“wikitext”,“WgSeparatorTransormTable”:[”“,”“,”,“WgDigitTransormTable”:[”“,”,“wgDefaultDateFormat”:“dmy”,“wgMonthNames”:[”“,“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”,“八月”,“九月”,“十月”,“十一月”,”WgmonthNameShort:“[”、“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”]、“wgRelevantPageName:“城堡”、“wgRelevantArticleId”:15933,“wgRequestId:“VxUR5gpAIDAAAEXY6FMAAACC”,“WgIsProbableEdit:”、“wgRestrictionMove:[]、“wgWikiEditorEnabledModules:”{“工具栏”:true,“对话框”:true,“预览”:false,”publish“:false},“wgBetaFeaturesFeatures”:[],“wgMediaViewerOnClick”:true,“wgMediaViewerEnabledByDefault”:true,“wgVisualEditor”:{“pageLanguageCode”:“en”,“pageLanguageDir”:“ltr”,“usePageImages”:true,“usePageDescriptions”:true},“wgPreferredVariant”:“en”,“wgRelatedArticles”:null,“WgRelatedArticleSuseCrusSearch”:true,”WgRelatedArticles SonlyUseCiruseArch“:false,“wgULSAcceptLanguageList:[],“WgulsCurrentAutonomy:“English”,“wgCategoryTreePageCategoryOptions:“{\”mode\”:0,“hideprefix\”:20,“showcount\”:true,“namespaces\”:false>,“wgNoticeProject:“wikipedia”,“WgCentralNoticeCategories:”wikipedia:“WgCentralNoticeCategaceousingAgacy:“[”筹款”,“筹款”,“WgCentralNoticeCategalothMobileDomain:“FawgWikibaseItemId:“Q23413”,“wgVisualEditorToolbarScrollOffset”:0});mw.loader.implement(“user.options”,function($,jQuery){mw.user.options.set({“variant”:“en”});});mw.loader.implement(“user.tokens”,function($,jQuery){\nmw.user.tokens.set({“editToken”:“+\\”,“patrolToken”:“+\\”,“watchToken”:“+\\”,“watchToken”+\”,“CsrToken”+\”;“+\\”);/@nomin*)/;\n});mw.loader.load([“mw.MediaWikiPlayer.loader”、“mw.PopUpMediaTransform”、“mw.TMHGalleryHook.js”、“mediawiki.page.startup”、“mediawiki.legacy.wikibits”、“ext.centralauth.centralautologin”、“mmv.head”、“ext.visualEditor.desktopArticleTarget.init”、“ext.uls.interface”、“ext.centralNotice.bannerController”、“skins.vector.js”];);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n来自维基百科的免费百科全书\n\n\n\n\n\n\t\t\t\t\t跳到:\t\t\t\t\t\t\t\t导航\t\t搜索\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n被充满水的护城壕包围的英格兰波迪亚姆城堡。\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n城堡是中世纪在欧洲和中东建造的一种防御结构。人们对“城堡”一词的含义存在争议。然而,它通常指的是贵族或贵族的私人建筑。这与堡垒不同,堡垒不是家,也不同于防御城镇,它是一种公共防御。大约900年来,城堡一直是一种私人建筑它们有许多不同的形状和不同的细节。\n城堡起源于9世纪和10世纪的欧洲。它们控制着周围的地方,可以帮助进攻和防御。武器可以从城堡中发射,也可以保护人们免受城堡中敌人的攻击。然而,城堡也是权力的象征。它们可以用来控制周围的人和道路。\n许多城堡最初是用泥土和木材建造的,通常使用手工劳动,然后用石头代替它们的防御。早期的城堡通常使用自然保护,没有塔楼。但到了12世纪末和13世纪初,城堡变得更长、更坚固更复杂。\n

file.writelines(str(soup.encode('UTF-8'))
有点疯狂,它是:

  • 将文本(
    str
    )编码为二进制(
    bytes
  • 通过在
    str
    中换行来获取该字节的文本表示形式(因此,您需要键入以重新创建二进制字节,但它不是原始二进制)
  • 每次将结果写入一个字符(
    writelines
    迭代您给定的内容,并
    str
    s按字符进行迭代)
  • 步骤#3既愚蠢又低效,但基本上是无害的。如果您将原始二进制文件写入打开进行二进制写入的文件,并实际写入
    字节
    对象,那么步骤#1就可以了。但是#1和#2一起意味着像新行这样的内容在输出中被转换为文字
    \n
    ,而不是实际断行。像
    é
    这样的非ASCII内容被输出为
    \xc3\xa9
    ,整个内容被包装在
    b''
    (或
    b''
    )中

    你想要的是:

    # open with UTF-8 encoding (in case your system defaults to something else)
    with open("TextOutput.txt", 'w', encoding='utf-8') as file:
        # Get the text and write it as a single block
        file.write(soup.get_text())
    

    输出看起来像什么?它确实感觉很疯狂。这产生了我所期望的,谢谢!我想我需要了解更多(我从file.open和file.write开始——假设我需要不同的语法/UTF-8编码)@user6217257:我猜你是在Windows上?在Windows上,默认编码通常不是你想要的;它是特定于区域设置的ASCII超集(用于英语和m)