我想要一个用户input
在Python中读取一个文件名(例如:text.txt
),但它读取的是字符串而不是文件类型。
r=(input("insert the name of the file"))
File= open(r,'r')
data=File.read()
data.split()
print(data)
答案 0 :(得分:3)
编辑:根据对我的回答的评论,OP希望为文件中的所有单词(空格分隔)构建包含dict
的{{1}}。
有一个非常棒的方法可以做到这一点,但它并没有真正教你任何东西,所以我会告诉你先做的很慢的方法,然后包括最佳的解决方案
{word:wordcount}
现在您可能希望过滤掉一些常用字词(wordcountdict = dict()
r = input("filename: ")
with open(r, 'r') as infile:
for line in infile:
for word in infile.split(): # split on whitespace
try:
wordcountdict[word.lower()] += 1
# try adding one to the word in the counter
except KeyError:
wordcountdict[word.lower()] = 1
# If the word isn't in the dict already, set it to 1
,"at"
,"I"
等),在这种情况下,您可以构建一个黑名单(类似{{1 }}并在"then"
内和blacklist = ['at', 'i', 'then']
块之前执行if word.lower() in blacklist: continue
。这将测试该单词是否在黑名单中,如果是,则跳过其余的执行。
现在我答应了一个很好的方法来做到这一点,那就是for word in infile.split()
。它是专门为列表中的元素计数而创建的字典。有更快的方法来计算单词,但在Python(imo)中没有更清晰的东西。您可以查看this question
try/except
如果您从未使用过来自collections.Counter
或from collections import Counter
wordcountdict = Counter()
r = input("filename: ")
with open(r, 'r') as infile:
for line in infile:
wordcountdict += Counter( map(str.lower,line.split()) )
功能的导入,这将是非常神秘的,这就是为什么我没有把它放在第一位! :)
基本上:collections
将一个参数作为一个可迭代的参数,并计算迭代中的所有元素(所以`Counter([1,1,2,3,4,4,4])== {1: 2,2:1,3:1,4:3})。您可以添加它们,并创建新的密钥,使它们独一无二,并在不是它们的地方添加值。
map
使用iterable的每个元素的参数运行collections.Counter
,并返回一个map(callable, iterable)
对象(它在Python2中为#{1}})可迭代的(所以callable
为您提供了一个地图对象,您可以通过迭代来获取map
,因为list
被调用了所有这些对象。
当我们将两者结合起来时,我们会在map(str.lower, ["ThIS", "Has", "UppEr", "aNd", "LOWERcase"])
中为["this","has","upper","and","lowercase"]
str.lower
个collections.Counter
个对象添加每个单词,然后将其添加到初始状态 - 将map
空line.split()
用作累加器。 Capisce?
目前还不清楚你的问题是什么问题,所以我只是为你抛出一些知识,希望有些东西可以帮助你。
Counter
这就是我想要做的事情......
r = input("insert the name of the file")
# this will be a string from the user, containing the file name, e.g.
# r == "text.txt"
# this is normal, because you pass `open` a filename, not a file object
File = open(r, "r")
# this makes File a file object that's pointed at the file name given from
# the user, opened for reading.
data = File.read()
# this sets data equal to the string containing the entire text in File
# This is usually NOT what you want to do, but without further explanation,
# I'll leave it be
data.split()
# this isn't an in-place operation, so you built a list out of the string
# data, split on newlines, then threw it away since you didn't assign it to
# anything.
print(data)
# prints your original data variable, because remember data.split() is not
# in-place, you'd have to do data = data.split(), but that's the wrong way
# to do that anyway....
这使用了上下文管理器(filename = input("insert the name of the file: ")
with open(filename, "r") as infile:
data = infile.readlines()
)而不是with
,因为这是一种更好的做法。它基本上使您不必在完成它之后键入File = open(filename)
,并且还解释了当您处理文件时事情可能出错,因此如果出于任何原因您代码抛出一个异常并且没有GET到你的File.close()
,它一旦离开File.close()
块就会关闭文件对象。
它还使用with
代替.readlines()
,这实际上是相同的。这可能不是你想要做的事情(在大多数情况下你只想迭代一个文件而不是将所有数据转储到内存中)但是如果没有更多的上下文,我无法进一步帮助你。
它也遵循PEP8的命名约定,其中.read().split()
是类。 Capitalizednames
不是一个类,它是一个文件对象,因此我将其命名为File
。我通常使用infile
和in_
作为文件名,但是YMMV。
如果您对自己尝试处理的文件发表评论,我可以为您编写一些特定的代码。
答案 1 :(得分:1)
我不介意在黑暗中拍摄。但如果你发布了一个要阅读的文件,它会有所帮助。并且您需要考虑现在知道他们应该键入哪个文件的人以及当他们没有键入您认为他们将键入的内容时会发生什么。
r = raw_input('type the name of the file: ')
with open(r,'r') as myfile:
for data in myfile:
print(data.split())