While trying to make a simple register/signup client only application for a personal project. I'm trying to load a list of users from a file, and compare them to a possible username. If the username already exists, the program will give them an error.
Here is a condensed clone of the code:
u1 = str(input("Input username: "))
t = open("userlistfile","r")
userlist = t.readline()
y = 0
for x in range(0, len(userlist)-1):
if userlist[y] == u1:
print("\n !Error: That username (",u1,") is already taken!")
y += 1
The user list is stored in a file so that it can opened, appended, and saved again, without being stored in the program. My current issue is that the userlist is saved as a string rather than an array. Is there a better way to do this? Thank you.
EDIT: Thanks to user lorenzo for a solution. My Friends are telling me to post a quick (really simple) copy of a for you guys who can't figure it out.
New code:
u1 = str(input("Input username: "))
t = open("userlistfile","r")
userlist = t.read() #Readline() changed to Read()
userlist = userlist.split('--') #This line is added
y = 0
for x in range(0, len(userlist)-1):
if userlist[y] == u1:
print("\n !Error: That username (",u1,") is already taken!")
y += 1
Example text file contents:
smith123--user1234--stacky
This line will seperate the string at the ('--') seperators and append each split part into an array:
userlist = userlist.split('--')
#Is used so that this (in the text file)
Smith123--user1234--stacky
#Becomes (in the program)
userlist = ['Smith123','user1234','stacky']
Sorry for the long post... Found it very interesting. Thanks again to Lorenzo :D.
userlist = t.readline()
reads one line from the file as a string. Iterating, then, gets characters in the string rather than words.
You should be able to get a list of strings (words) from a string with the split() method of strings or the more general re.split() function.
Related
The setup: A UITextField and a Tableview with suggested users
I try to have the following result:
I want users to be able to link other users.
Its working fine as long as I search with my last word in the array
let caption = captionTextView.text
let words = caption?.components(separatedBy: .whitespacesAndNewlines)
guard let searchingWord = words?.last else {return}
if searchingWord.hasPrefix("#") {
self.indicator.startAnimating()
let search = searchingWord.trimmingCharacters(in: CharacterSet.punctuationCharacters).lowercased()
}
But in case a user wants to adjust a username in the middle or at least not at the end of the array, the searching functions doesn't work properly as it still searches with the last word in the array
Example:
"Hey how are you #Lisa #Marcel #Thomas"
In case a user wants to change "#Lisa" to "#Lisbeth" the search function will search with Thomas as its the last word in the array
I wasn't able to get the word I am working at, only last and first words in the array, however I am able to get the current cursor location with
let cursor = captionTextView.cursorOffset!
which is an extension.
So how do I get the word I am working at up until the next "#" to the left und the next blank space to the right? Thanks in advance!
Maybe try something like this:
if let selectedRange = textview.selectedTextRange {
let cursorOffset = textview.offset(from: textview.beginningOfDocument, to: selectedRange.start)
let text = textview.text
let substring = text?.prefix(cursorOffset)
let editedWord = substring?.split(separator: "#")
}
(written on a phone, and untested)
One solution is Regular Expression
let string = "Hey how are you #Lisa #Marcel #Thomas"
let searchingWord = "Lisa"
let replacingWord = "Lisbeth"
let pattern = "#\(searchingWord)\\s"
string.replacingOccurrences(of: pattern, with: "#\(replacingWord) ", options: .regularExpression)
The pattern searches for # followed by the searching word followed by a whitespace character.
Since you say things are working the way you want if the last word is the one that has a username in it you just need to loop over all the words. Depending on your needs you may need to keep track of the usernames that were in the text before to save you from searching for the same user multiple times, but an array of used usernames should sort that for you.
Also, unless you want to prevent users from having underscores and the such in their names you should tweak the way in which you remove the # symbol as well.
guard let words = captionTextView.text?.components(separatedBy: .whitespacesAndNewlines) else { return }
for word in words where word.hasPrefix("#") {
self.indicator.startAnimating()
let search = word.replacingOccurrences(of: "#", with: "").lowercased()
}
Sticking the above code into a playground that uses the sample string you supplied in place of captionTextView.text? and printing search each time yielded…
lisa
marcel
thomas
I am trying to read a file within a controller and store some data in an object, but I cant manage to save it properly. Can anyone help? I am new in Groovy/Grails...
File generals = new File("C:/Grails/Grails-3.3.0/ggts/Test/data.txt")
def line = generals.readLines()
def date = new SetDate(params)
date.save()
date.title = ${line[0]}
date.location = ${line[1]}
date.description = ${line[2]}
date.name = ${line[3]}
date.email = ${line[4]}
date.save()
You may change ${line[0]} to "${line[0]}" and all things alike if you want to use string interpolation.
And as line is a list of String, change ${line[0]} to line[0] is also ok.
I face this issue and can't seem to find a fix except with Scipy or Numpy, both of which I don't wanna use in this case.
From a .csv file, I want to extract the values of the first column :
enter image description here
Which I manage to do with the following code :
mat_data = open('file.csv')
data_reader = csv.reader(mat_data)
list_data = list(data_reader)
value1=float(list_data[1][0])
value2=float(list_data[2][0])
value3=float(list_data[3][0])
I'd now like to create a loop that could be used and create value"i" no matter how many lines long my .csv is.
Any idea?
This did the trick for me !
mat_data = open('file.csv')
data_reader = csv.reader(mat_data)
list_data = list(data_reader)
i=0
value=dict()
for i in range(1,len(list_data)):
value[i]=list_data[i][0]
print value[i]
I'm really fresh to Python and need help reading information from txt file. I have a large C++ app need to duplicate it in Python. Sadly I have no idea where to start. I've been reading and watching some tutorials, but little help from them and I'm running out of time.
So my task is:
I have a shopping list with:
-Name of the item, price and age.
I also need to create two searches.
Search whether the item is in the shop (comparing strings).
if name of the item is == to the input name.
Search by age. Once the program finds the items, then it needs to print the list according to the price - from the lowest price to the highest.
For example you input age 15 - 30, the program prints out appropriate
items and sorts them by the price.
Any help would be nice. At least from where I could start.
Thank you.
EDITED
So far, I have this code:
class data:
price = 0
agefrom = 0
ageto = 0
name = ''
# File reading
def reading():
with open('toys.txt') as fd:
toyslist = []
lines = fd.readlines()
for line in lines:
information = line.split()
print(information)
"""information2 = {
'price': int(information[1])
'ageftom': int(information[2])
'ageto': int(information[3])
#'name': information[4]
}"""
information2 = data()
information2.price = int(information[0])
information2.agefrom = int(information[1])
information2.ageto = int(information[2])
information2.name = information[3]
toyslist.append(information2)
return toyslist
information = reading()
I HAVE A PROBLEM WITH THIS PART. I want to compare the user's input with the item information in the txt file.
n_search = raw_input(" Please enter the toy you're looking for: ")
def name_search(information):
for data in information:
if data.name == n_search:
print ("We have this toy.")
else:
print ("Sorry, but we don't have this toy.")
If you want to fins something in a list it's generally as straightforward as:
if "apple" in ["tuna", "pencil", "apple"]
However, in your case, the list to search is a list of lists so you need to "project" it somehow. List comprehension is often the easiest to reason about, a sort of for loop in a for loop.
if "apple" in [name for name,price,age in [["tuna",230.0,3],["apple",0.50,1],["pencil",1.50,2]]]
From here you want to start looking at filters whereby you provide a function that determines whether an entry is matched or not. you can roll your own in a for loop or use something more functional like 'itertools'.
Sorting on a list is also easy, just use 'sorted(my_list)' supplying a comparator function if you need it.
Examples as per your comment...
class ShoppingListItem:
def __init__(self,name,price,age):
self.name=name
self.price=price
self.age=age
or
from collections import namedtuple
sli = namedtuple("ShoppingListItem",['name','age','price'])
My code has 2 parts. First part is an automatic file opening programmed like this :
fichierref = 'H:\MATLAB\Archive_08112012';
files = dir(fullfile(fichierref, '*.txt'));
numberOfFiles = numel(files);
delimiterIn = ' ';
headerlinesIn = 11;
for d = 1:numberOfFiles
filenames(d) = cellstr(files(d).name);
end
for i=1:numberOfFiles
data = importdata(fullfile(fichierref,filenames{i}),delimiterIn,headerlinesIn);
end
Later on, I want the user to select his files for analysis. There's a problem with this though. I typed the lines as follow :
reference = warndlg('Choose the files from which you want to know the magnetic field');
uiwait(reference);
filenames = uigetfile('./*.txt','MultiSelect', 'on');
numberOfFiles = numel(filenames);
delimiterIn = ' ';
headerlinesIn = 11;
It's giving me the following error, after I press OK on the prompt:
Cell contents reference from a non-cell array object.
Error in FreqVSChampB_no_spec (line 149)
data=importdata(filenames{1},delimiterIn,headerlinesIn);
I didn't get the chance to select any text document. Anyone has an idea why it's doing that?
uigetfile is a bit of an annoying when used with `MultiSelect': when you select multiple files the output is returned as a cell array (of strings). However, when only one file is selected the output is of type string (not a cell array with a single cell, as one would have expected).
So, in order to fix this:
filenames = uigetfile('./*.txt','MultiSelect', 'on');
if ~iscell(filenames) && ischar( a )
filenames = {filenames}; % force it to be a cell array of strings
end
% continue your code here treating filenames as cell array of strings.
EDIT:
As pointed out by #Sam one MUST verify that the user did not press 'cancel' on the UI (by checking that filenames is a string).