python - “你”如何将整个标题保存为字符串?
问题描述
在 Python 中,如果您假设必须将上述字符串保存到变量中,您将如何保存?
编辑:我假设的情况是,如果您有一个函数,可以将网站/PDF 的内容复制到一个变量(例如使用 Pyperclip),然后对该变量执行某些操作。有一个单引号、双引号、三个单引号和三个双引号将立即导致迄今为止提出的每个解决方案中的错误。
解决方案
如果您尝试将其键入为字符串,它将不起作用。但是,如果您将数据行拉入变量中,Python 将自动反斜杠chars
它需要。
如果您尝试使用open()
and从文件中提取此行,这一点很明显,如果您使用 解析文件readlines()
,您将得到相同的结果。HTML
BeautifulSoup
文件包含:
How ' would " you ''' save """ this whole title as a string?
打开和readlines()
:
with open('data.txt', 'r') as file:
test = list(file.readlines())
print(test)
输出:
['How \' would " you \'\'\' save """ this whole title as a string?']
HTML
文件:
<doctype='HTML'>
How ' would " you ''' save """ this whole title as a string?
</>
来自HTML
:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('data.html'), "html.parser")
text = soup.get_text()
print(type(text), text.strip())
输出:
<class 'str'> How ' would " you ''' save """ this whole title as a string?
当您将其附加到列表时,它会返回包含字符转义的字符串。
test.append(text.strip())
print(test)
输出:
['How \' would " you \'\'\' save """ this whole title as a string?']
推荐阅读
- php - 如何在 Codeigniter 中获取 CKEditor 值?
- php - 不支持编码格式 (tmp)
- mysql - 从 MySql 导入 Sqoop 失败,线程“main”java.lang.NoClassDefFoundError 出现异常
- python - pipenv 如何将 Pipfile 与项目的入口点相关联?
- javascript - 如何将上下文使用者传递给仅由 React Router 呈现的组件(Event.js)?
- php - 使用 ajax 更新 mysql 结果(设置为已删除)而不刷新页面?
- flutter - 如何删除卡片中的行之间的空间(Flutter)
- c# - 如何在另一个表单任务中调用表单
- php - 使用 Twig 模板访问 cookie 值
- django - 关于 Django 为存储在 AmazonS3 上的图像添加扩展名/文件夹名称的错误