我正在尝试读取网页并将格式化文本输出到文本文件。下面的代码使用格式打印到shell,但是当我将它写入文件时,它将它放在一行上(文本中出现换行符/ n)。与生成的文本文件相比,为什么Python 3 shell中的文本格式不同?
我尝试了各种各样的东西,如不将它转换为字符串,使用从美丽的汤美容但没有似乎产生格式文本文件。我假设我错过了一些相当基本的东西。任何帮助或指导将不胜感激。
# 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 - 简单的英文维基百科,自由的百科全书\ ndocument.documentElement.className = document.documentElement.className .replace(/(^ | \ s)client-nojs(\ s | $)/,“$ 1client-js $ 2”); \ n(window.RLQ = window.RLQ || [])。push(function ){mw.config.set({ “wgCanonicalNamespace”: “”, “wgCanonicalSpecialPageName”:假 “wgNamespaceNumber”:0 “wgPageName”: “城堡”, “wgTitle”: “城堡”, “wgCurRevisionId”:5333370, “wgRevisionId”:5333370“wgArticleId”:15933“wgIsArticle”:true,“wgIsRedirect”:false,“wgAction”:“view”,“wgUserName”:null,“wgUserGroups”:[“”], wgCategories “:” 城堡 “],” wgBreakFrames “:假的,” wgPageContentLanguage “:” 恩”, “wgPageContentModel”: “wikitext的”, “wgSeparatorTransformTable”: “”, “”], “wgDigitTransformTable”: “” “”], “wgDefaultDateFormat”: “日月”, “wgMonthNames”: “”, “月”, “日”, “月”, “月”, “五一”, “六一”, “七一”,”八五 “ ”九五“, ”十月“, ”月“, ”月“], ”wgMonthNamesShort“: ”“, ”月“, ”月“, ”月“, ”月“, ”月“,” 君“ ”月“, ”月“, ”月“, ”月“, ”月“, ”月“], ”wgRelevantPageName“: ”青山“, ”wgRelevantArticleId“:15933, ”wgRequestId“: ”VxUR5gpAIDAAAEXY6FMAAACC“,” wgIsProbablyEditable “:真实的,” wgRestrictionEdit “:[],” wgRestrictionMove “:[],” wgWikiEditorEnabledModules “:{” 工具栏 “:真正的” 对话 “:真正的” 预览 “:假的,” 出版 “:假},” wgBetaFeaturesFeatures “:[],” wgMediaViewerOnClick “:真” wgMediaViewerEnabledByDefault “:真” wgVisualEditor “:{” pageLanguageCode “:” EN”, “pageLanguageDir”: “LTR”, “usePageImages”:真 “usePageDescriptions”:真}, “wgPreferredVariant”: “恩”, “wgRelatedArticles”:空, “wgRelatedArticlesUseCirrusSearch”:真实的,“WG RelatedArticlesOnlyUseCirrusSearch “:假” wgULSAcceptLanguageList “:[],” wgULSCurrentAutonym “:” 英语 “ ”wgCategoryTreePageCategoryOptions“: ”{\“ 模式\ ”:0,\“ hideprefix \ ”:20,\“ showcount \”:真, \ “命名空间\”:假}”, “wgNoticeProject”: “维基百科”, “wgCentralNoticeCategoriesUsingLegacy”:[ “筹款”, “筹款”], “wgCentralAuthMobileDomain”:假 “wgWikibaseItemId”: “Q23413”, “wgVisualEditorToolbarScrollOffset”: 0}); mw.loader.implement( “user.options”,功能($,jQuery的){mw.user.options.set({ “变体”: “EN”});}); mw.loader.implement (“user.tokens”,函数($,jQuery){\ nmw.user.tokens.set({“editToken”:“+ \\”,“patrolToken”:“+ \\”,“watchToken”:“ \\“,”csrfToken“:”+ \\“});/ @nomin * /; \ n \ 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.init “ ”ext.uls.interface“,” ext.centralNot ice.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 \ nCastle \ 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一座城堡(来自拉丁词“castellum”)是中世纪在欧洲和中东建造的一座坚固的建筑。人们争论城堡这个词的含义。但是,它通常意味着贵族或贵族的私人结构。这不同于一个不是住宅的堡垒,也不是一个防御性强的城镇。大约900年前的城堡建成后,他们拥有许多不同的形状和不同的细节。\ n城堡在9世纪和10世纪始于欧洲。他们控制着他们周围的地方,可以帮助攻击和防守。武器可以从城堡发射,或者可以保护城堡中的敌人。但是,城堡也是权力的象征。他们可以用来控制周围的人和道路。\ n许多城堡一开始经常使用体力劳动,用泥土和木头建造,然后用石头代替它们的防御。早期的城堡通常使用自然保护,并没有塔。在晚12和早期的13世纪,虽然,城堡变得更长,更复杂\ n
是什么,输出什么样子的? – ShadowRanger
http://stackoverflow.com/questions/13730107/writelines-writes-lines-without-newline-just-fills-the-file –